How to add a CSS class to an element with React function components

Active3 hr before
Viewed126 times

10 Answers


Pass a string as the className prop:,It is common for CSS classes to depend on the component props or state:,Note that this functionality is not a part of React, but provided by third-party libraries. React does not have an opinion about how styles are defined; if in doubt, a good starting point is to define your styles in a separate *.css file as usual and refer to them using className.,“CSS-in-JS” refers to a pattern where CSS is composed using JavaScript instead of defined in external files.

load more v

Thanks for your attempt of help. But i got other solution based on ordinary functon inside component – Ren Jitsm Jul 13 at 8:56 ,i would like to know how can i add a CSS class to an element which has no any CSS classes.I am looking React Functional component solution with Hooks. Here i want to add class to tag and i don't need to add ${myclass} in advance. That means tag should be without any attributes before we execute the addclass functionality. I tried the following method and needs to get a best practice on it. Thanks in advance!,Computational Science,and then in the function

in the element you want to change its className

 <h1 className={`${myclass}`} id = "change-class">Hi</h1>

and then in the function

  const addclass = () => {

so the whole code would look like this

function Trial(){
 const addclass=()=>{

     <h1 className={`${myclass}`} id = "change-class" >Hi</h1>
      <button onClick={addclass}>Click it</button>
load more v

Here is a simple example of adding CSS classes conditionally.,If we want to update/add CSS class when the component is updated or the state/props of components change then we have to conditionally apply the CSS based on the state/props value. ,ISRO CS Syllabus for Scientist/Engineer Exam,The class hidden will be applied when the value of the flag is true otherwise only the box CSS class will be applied.

Here is a simple example of adding CSS classes conditionally.

 <div className={`box ${flag === false ? "" : "hidden"}`}>

npx create - react - app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start
load more v

But great tutorial, it really helped me to understand the concept.,Let’s have a walk through this concept. I put together a little example, where we show and hide a box with the click of a button.,Next, let’s take a look at our button within our render function. Whenever the user clicks our button, it will toggle the boolean value for isBoxVisible. As you can see, we pass our toggleBox function to the button’s onClick event. Each time the button is pressed, it will toggle the boolean value for isBoxVisible in the component’s state.,At the beginning, we initialize our state object. It has a boolean value isBoxVisible that is initially set to false.

state = {
   isBoxVisible: false
load more v

How To Style React Components , How To Manage State on React Class Components , How To Manage State with Hooks on React Components , How To Customize React Components with Props

To start, make a new project. In your terminal, run the following script to install a fresh project using create-react-app:

npx create - react - app styling - tutorial
load more v

There seems to be a number of ways of styling React components used widely in the industry for production level work:,You can learn more about this approach in the JSS official documentation. There’s also a way to try it out using their REPL (read-eval-print loop).,There are a number of other CSS-in-JS libraries to consider depending on your needs. Some popular examples include:,I don’t think anyone needs an introduction to inline CSS. This is the CSS styling sent to the element directly using the HTML or JSX. You can include a JavaScript object for CSS in React components, although there are a few restrictions such as camel casing any property names which contain a hyphen. You can style React components in two ways using JavaScript objects as shown in the example.


import React from "react";

const spanStyles = {
  color: "#fff",
  borderColor: "#00f"

const Button = props => (
  <button style={{
    color: "#fff",
    borderColor: "#00f"
    <span style={spanStyles}>Button Name</span>
load more v

// Typical component with state-classes
<ul className="todo-list">
 className={classnames({ 'todo-list__item': true, 'is-complete': item.complete })}>

// Using inline-styles for state
<li className='todo-list__item'
 style={(item.complete) ? styles.complete : {}} />

Automatic vendor prefixing You can use standard CSS properties, and styled components will add vendor prefixes should they be needed.,Elimination of dead styles Styled components remove unused styles, even if they’re declared in your code.,The CSS preprocessor Stylis enables styled components to support SCSS-like syntax, such as nesting:,Unique class names Styled components are independent of each other, and you do not have to worry about their names because the library handles that for you.

import styled from "styled-components";

const StyledButton = styled.button`
  min-width: 200px;
  border: none;
  font-size: 18px;
  padding: 7px 10px;
  /* The resulting background color will be based on the bg props. */
  background-color: ${props => === "black" ? "black" : "blue";

function Profile() {
  return (
      <StyledButton bg="black">Button A</StyledButton>
      <StyledButton bg="blue">Button B</StyledButton>
load more v

When creating a React component, the component's name must start with an upper case letter.,Create a Function component called Car,Create a Class component called Car,Refer to the Car component as normal HTML (except in React, components must start with an upper case letter):

Create a Class component called Car

class Car extends React.Component {
  render() {
    return <h2>Hi, I am a Car!</h2>;
load more v

styled-components has full theming support by exporting a <ThemeProvider> wrapper component. This component provides a theme to all React components underneath itself via the context API. In the render tree all styled-components will have access to the provided theme, even when they are multiple levels deep.,If you ever need to use the current theme outside styled components (e.g. inside big components), you can use the withTheme higher order component.,You can also use useContext to access the current theme outside of styled components when working with React Hooks.,The error thrown - Cannot call a class as a function - occurs because the styled component is attempting to call the component as an interpolation function.

// Define our button, but with the use of props.theme this timeconst Button = styled.button`  font-size: 1em;  margin: 1em;  padding: 0.25em 1em;  border-radius: 3px;
  /* Color the border and text with theme.main */  color: ${props => props.theme.main};  border: 2px solid ${props => props.theme.main};`;
// We are passing a default theme for Buttons that arent wrapped in the ThemeProviderButton.defaultProps = {  theme: {    main: "palevioletred"  }}
// Define what props.theme will look likeconst theme = {  main: "mediumseagreen"};
render(  <div>    <Button>Normal</Button>
    <ThemeProvider theme={theme}>      <Button>Themed</Button>    </ThemeProvider>  </div>);
load more v

Other "function-element" queries related to "How to add a CSS class to an element with React function components"