Switching a conditional className to a styled component

Currently, I am in the process of converting my project from plain CSS to styled components using styled-components. So far, I have successfully converted all of my components except for one. I have looked at various examples on Stack Overflow but none of them quite match what I need.

The component causing me trouble is the InfoBox component, which has conditional class names. My question is: how do I convert the InfoBox component to use styled components? Do I need to inject the styles using a styled-component wrapper or is there another way?

I apologize if there are any mistakes in my English as it is not my native language.

Here is a snippet of my code:

import React from 'react'
import "./InfoBox.css"

function InfoBox({ isRed, active, activetored, ...props }) {
    return (
        <div onClick={props.onClick}
            className={`infoBox ${active && "infoBox--selected"} 
            ${activetored && "infoBox--selectedtored"}
            ${isRed && "infoBox--red"} `} >
           
        </div>
    )
}

export default InfoBox

Here is an example of how the InfoBox component is used in the app:

<div className="app__stats">
      <InfoBox
        isRed
        active={typeofCase === "cases"}
        onClick={(e) => setTypeofCase('cases')}
       
      />
      <InfoBox
        isGreen
        active={typeofCase === "recovered"}
        onClick={(e) => setTypeofCase('recovered')}
     
      />
      <InfoBox
        isRed
        activetored={typeofCase === "deaths"}
        onClick={(e) => setTypeofCase('deaths')}
       
      />
    </div>

An example of the CSS styling for the InfoBox component can be seen below (though you can customize this in any way):

.infoBox--selected {
  border-top: 10px solid greenyellow;
}

.infoBox--selectedtored {
  border-top: 10px solid red;
}

.infoBox--red {
  border-color: darkblue;
}

Answer №1

One of the main principles behind styled-components is to eliminate the need for traditional classnames. Instead of relying on classes for styling, there are several options available. A simple approach is to incorporate your props directly into the CSS code, allowing you to dynamically adjust the style based on the component's properties:

const InfoBox = styled.div`
  border-color: ${props => props.isRed ? 'darkblue' : 'black'};
  border-top: ${props => props.active ? '10px solid greenyellow' : 'red'};
  ...
`;

This approach eliminates the need for explicit class assignments (although it can still be utilized if needed). Simply use the InfoBox styled component within your component, and you're all set.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we retrieve the initial data of components in the _app.js page?

My website's navigation bar relies on dynamic data fetched from an API using the getStaticProps method. Since I want the navigation bar to be displayed on all pages, placing it in the _app.js component seems like the best option. However, the issue is ...

Encountered an error while running `npm init @eslint/config` and `npx create-react-app .`

When attempting to initialize an eslint config file for my node project using npm init @eslint/config, I encountered the following error. I've tried downgrading my node version, upgrading npm to the latest version, and clearing node cache, but nothing ...

What steps should I take to stop the accidental triggering of methods in an Unmounted class component?

I have been working on a React-Redux application that incorporates Google oauth2 login functionality. To manage the login and logout processes, I created a dedicated component called GoogleAuth. Usually, the GoogleAuth component is placed in the Header co ...

Having trouble getting the overflow scrollbar to work properly?

I recently created a Whiteboard using Vue. The Whiteboard consists of an SVG element where I can add other SVG elements like paths to it. In order to enable scrolling within the SVG, I came across this example which seemed quite helpful. Check out the exa ...

Streamlining the process of implementing click events on elements selected by class using jQuery

Slowly but surely, I am gaining familiarity with jQuery and have reached the point where I desire to abstract my code. However, I am encountering issues when attempting to define click events during page load. Within the provided code snippet, my objectiv ...

When applying a cell formatter to change the color of a Tabulator cell, the text displayed is being

I am attempting to dynamically change the color of a tabulator cell based on its input. My initial approach was to simply try changing the cell's color. After running the following code, here is what I observed: function testFormatter(cell, formatt ...

Ensure that you patiently wait for the axios method to finish execution before moving on to the

I am currently learning vue.js and struggling with the concept of promises. I need to initialize a variable with data from an API call, but I want to ensure that the Axios call is generic: { data: { list: [], }, methods: { ShowList: function ...

iOS Webkit is causing an override of the CSS property text-align for the submit button

Here is the CSS code I used for styling a form's submit button: .submit { -webkit-appearance: none !important; text-align: center !important; border-radius: 0rem; color: rgb(63, 42, 86); display: inline-block; float: right; ...

Unable to interact with web element using JavaScript

Struggling to find a solution for simulating a click on a button element on Outlook.com mobile website using JavaScript. Despite numerous attempts from online sources, the button remains unresponsive to clicks. An interesting discovery was made that the c ...

New solution for Java applet requiring communication with browser using JavaScript

Within our web platform, we have been utilizing a Java applet to interact with the MS Word application using jacob jar. This allows users to open, edit, and automatically upload files to the server upon saving. However, due to Google Chrome discontinuing ...

Exploring a JSON tree recursively and combining its branches

I am attempting to navigate a recursive json tree (json2) and combine it with another json (json), matching identifiers. It's important to note that when objects are present, they may contain either objects or object, but the identifier will always be ...

VueJS component fails to properly sanitize the readme file, as discovered by Marked

Could someone explain why the output from the compiledMarkdown function is not sanitized, resulting in unstyled content from the markdown file? <template> <div style="padding:35px;"> <div v-html="compiledMarkdown" ...

Tips for shifting an image upwards and extending it beyond one section while keeping the other section unaffected

Struggling all day while designing a CSS site, trying to hide one part of an image when it overflows and keep another part visible, in addition to moving the image up and down. Here's the HTML code snippet: <section class="next-gen"&g ...

Tips for adding information into IndexedDB after receiving an AJAX response:

If I were to start by setting up the database outside of my Ajax call like this: // This code is compatible with all devices and browsers, utilizing IndexedDBShim as a last resort var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitInd ...

What steps should I take to resolve the problem with accessing Mongodb?

Whenever I attempt to initialize MongoDb by typing 'mongo', I keep getting the error message "not recognized as an internal or external command". Despite setting the environment variables as recommended by many, as shown in this screenshot, I am ...

Toggling the form's value to true upon displaying the popup

I have developed an HTML page that handles the creation of new users on my website. Once a user is successfully created, I want to display a pop-up message confirming their creation. Although everything works fine, I had to add the attribute "onsubmit= re ...

converting HTML values to TypeScript

I'm a beginner with Angular and could use some assistance. Currently, I have two components - one for the index and another for navigation. Within the index component, there are subcomponents that change based on the value of a variable called produ ...

Issues with Mocha's beforeEach() and done() functions not functioning as expected

I am facing an issue with my Mocha test suite. When I run the 'make test' command, I encounter the following error message: Uncaught TypeError: Object [object Object],[object Object] has no method 'done' Below is the relevant code sni ...

Adjust picture dimensions when the window changes (using jQuery)

Hey there, I'm in need of some help resizing images on my webpage. I want the images to adjust their size when the page loads or when the browser is resized. The images can be either portrait or landscape, and they will be contained within a div that ...

Postgres Array intersection: finding elements common to two arrays

I'm currently developing a search function based on tags, within a table structure like this CREATE TABLE permission ( id serial primary key, tags varchar(255)[], ); After adding a row with the tags "artist" and "default," I aim ...