React js add css class

Styling and CSS

It is common for CSS classes to depend on the component props or state:

render()  let className = 'menu'; if (this.props.isActive)  className += ' menu-active'; > return span className=className>>Menuspan> >

Tip

If you often find yourself writing code like this, classnames package can simplify it.

Yes, see the docs on styling here.

CSS classes are generally better for performance than inline styles.

“CSS-in-JS” refers to a pattern where CSS is composed using JavaScript instead of defined in external files.

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 .

Can I do animations in React?

React can be used to power animations. See React Transition Group, React Motion, React Spring, or Framer Motion, for example.

Источник

Styling and CSS

It is common for CSS classes to depend on the component props or state:

render()  let className = 'menu'; if (this.props.isActive)  className += ' menu-active'; > return span className=className>>Menuspan> >

Tip

If you often find yourself writing code like this, classnames package can simplify it.

Yes, see the docs on styling here.

CSS classes are generally better for performance than inline styles.

“CSS-in-JS” refers to a pattern where CSS is composed using JavaScript instead of defined in external files.

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 .

Can I do animations in React?

React can be used to power animations. See React Transition Group, React Motion, React Spring, or Framer Motion, for example.

Источник

Styling and CSS

It is common for CSS classes to depend on the component props or state:

render()  let className = 'menu'; if (this.props.isActive)  className += ' menu-active'; > return span className=className>>Menuspan> >

Tip

If you often find yourself writing code like this, classnames package can simplify it.

Yes, see the docs on styling here.

CSS classes are generally better for performance than inline styles.

“CSS-in-JS” refers to a pattern where CSS is composed using JavaScript instead of defined in external files. Read a comparison of CSS-in-JS libraries here.

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 .

Can I do animations in React?

React can be used to power animations. See React Transition Group and React Motion, for example.

Источник

React: Programmatically Add/Remove CSS Classes

This succinct, practical article shows you how programmatically add/remove CSS classes to/from an element in React. We can get the job done without installing any third-party libraries.

Overview

You can add/remove single or multiple classes to/from an element with an event handler function or by using the useRef hook.

With an event handler function:

// define the event handler function const buttonClickHandler = (e) => < e.currentTarget.classList.remove('light'); e.currentTarget.classList.add('dark'); >; // set onClick or other event props on your element 

With the useRef() hook:

/* Fefine a ref */ const kindaCodeRef = useRef(); /* Tie the ref with a certain element */ 
>
/* Add and Remove many classes at once */ kindaCodeRef.current.classList.remove('class-1', 'class-2', 'class-3'); kindaCodeRef.current.classList.add('class-4', 'class-5', 'class-6');

You can also toggle a class name like so:

kindaCodeRef.current.classList.toggle('dark-backgorund'); kindaCodeRef.current.classList.toggle('light-background');

For more clarity, see the complete, working example below.

Example

App Preview

The tiny React project we’re going to build presents a text input and box that contains a message. A name entered into the text input is considered valid if its length is equal to or more than 3 characters. The color of the box can be one of the following:

  • Gray: If the input is empty
  • Red: If the name provided is from 1 to 3 characters
  • Blue: If the name entered is valid

Another component of our React app is a button that can change its background color on click.

The Code

1. Initialize a new React project by performing the command below:

npx create-react-app kindacode-example

As of now, we’ll focus on these 2 files: src/App.js and src/App.css. Other files will be intact.

2. Replace all of the default code in your src/App.js with the following (you can see explanations in the comments):

// KindaCode.com // src/App.js import < useRef, useState >from 'react'; import './App.css'; function App() < const messageRef = useRef(); const [message, setMessage] = useState( 'If your name is less than 3 characters, it will be rejected.' ); // this function will be triggered when the input changes const inputChangeHandler = (e) => < const enteredText = e.target.value; // In the beginning or when the user deletes everything, use the default style if (enteredText.length === 0) < setMessage( 'If your name is less than 3 characters, it will be rejected.' ); messageRef.current.classList.remove('message--error', 'message--success'); messageRef.current.classList.add('message--default'); >else if (enteredText.length < 3) < setMessage('Your name is too short.'); messageRef.current.classList.remove( 'message--default', 'message--success' ); messageRef.current.classList.add('message--error'); >else < setMessage('Your name is valid.'); messageRef.current.classList.remove('message--default', 'message--error'); messageRef.current.classList.add('message--success'); >>; // this function is called when the button gets clicked const buttonClickHandler = (e) => < e.currentTarget.classList.toggle('button--dark'); e.currentTarget.classList.toggle('button--light'); >; return ( <> 

Welcome to KindaCode.com

placeholder='Enter your name' className='input' />
className='message message--default'>
); > export default App;

3. Empty your src/App.css file, then add the following:

.container < width: 80%; margin: 50px auto; >/* classes related to the text input and the message */ .input < width: 300px; padding: 10px 10px; border: 1px solid #bbb; border-radius: 5px; >.message < margin-top: 20px; padding: 20px; border-radius: 5px; >.message--default < background-color: #f1f1f1; color: #333; >.message--error < background: #e53935; color: white; >.message--success < background: #1565c0; color: white; >/* classes related to the button */ .button < margin-top: 50px; padding: 12px 30px; font-size: 16px; border: none; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); cursor: pointer; >.button--light < background: #eee; color: #666; >.button--dark

4. Boot it up and go to http://localhost:3000 to see the result.

Conclusion

You’ve learned the technique to add and remove CSS classes in React without using any third-party packages. If you want to consolidate your programming skills and explore more new and interesting things in the modern React world, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Источник

React js add css class

Last updated: Jan 17, 2023
Reading time · 4 min

banner

# Table of Contents

# Add a class to the Body element in React

To add a class to the body element in React:

  1. Access the body element as document.body in useEffect or an event handler.
  2. Use the classList.add() method to add a class to the body tag.
  3. For example, document.body.classList.add(‘my-class’) .
Copied!
import useEffect> from 'react'; import './App.css'; export default function App() useEffect(() => // 👇 add class to body element document.body.classList.add('bg-salmon'); // 👇️ adding multiple classes to the body element document.body.classList.add( 'bg-salmon', 'my-class-1', 'my-class-2', 'my-class-3', ); // 👇️ removing classes from body element document.body.classList.remove('my-class-3'); // 👇️ checking if the body element contains a class if (document.body.classList.contains('bg-salmon')) console.log('body tag contains class'); > >, []); return ( div> h2>bobbyhadz.comh2> div> ); >

And here is the CSS for the example.

Copied!
.bg-salmon background-color: salmon; color: white; >

react add class to body

We used the classList.add() method to add a class to the body element.

Copied!
document.body.classList.add('bg-salmon');

We can access the body element on the document object.

We passed an empty dependencies array to the useEffect hook because we only want to add the class to the body element once — when the component mounts.

If you need to remove the classes when the component unmounts, return a cleanup function from the useEffect hook.

Copied!
useEffect(() => // 👇 add class to body element document.body.classList.add('bg-salmon'); return () => // 👇️ removing classes from body element // when the component unmounts document.body.classList.remove('my-class-3'); > >, []);

If you need to check if an element contains a class, click on the following article.

# Adding multiple classes to the body element in React

You can pass as many classes to the classList.add() method as necessary.

Copied!
document.body.classList.add( 'bg-salmon', 'my-class-1', 'my-class-2', 'my-class-3', );

If you need to remove one or more classes from the body tag, use the classList.remove() method.

Copied!
document.body.classList.remove( 'my-class-1', 'my-class-2', )

# Adding a class to the body element when an event occurs

You can also add a class to the body element when an event occurs, e.g. a button is clicked.

Copied!
import './App.css'; export default function App() const handleClick = () => // 👇️ add class to the body element document.body.classList.add('bg-salmon'); // 👇️ toggle class on the body element // document.body.classList.toggle('bg-salmon'); >; return ( div> button onClick=handleClick>>Clickbutton> div> ); >

We set the onClick prop on the button element, so every time it is clicked, the handleClick function gets invoked.

# Toggle a class on the body element in React

If you need to toggle a class on the body element when an event occurs, use the classList.toggle method.

Copied!
import './App.css'; export default function App() const handleClick = () => // 👇️ toggle class on the body element document.body.classList.toggle('bg-salmon'); >; return ( div> button onClick=handleClick>>bobbyhadz.combutton> div> ); >

The classList.toggle method removes an existing class from the element if the class is present. Otherwise, it adds the class to the element.

# Set styles on the Body element in React

To set styles on the body element in React:

  1. Access the body element as document.body in useEffect or an event handler.
  2. Use the style property to set styles on the body element.
  3. For example, document.body.style.backgroundColor = ‘lime’ .
Copied!
import useEffect> from 'react'; import './App.css'; export default function App() useEffect(() => // 👇 add class to body element document.body.classList.add('bg-salmon'); // 👇️ set style on body element document.body.style.backgroundColor = 'salmon'; return () => // 👇️ optionally remove styles when component unmounts document.body.style.backgroundColor = null; document.body.classList.remove('bg-salmon'); >; >, []); return ( div> h2>bobbyhadz.comh2> div> ); >

And here is the CSS file for the example.

Copied!
.bg-salmon background-color: salmon; color: white; >

We can access the body element on the document object.

You can use the style object to read an element’s styles or set new styles on the element.

Copied!
document.body.style.backgroundColor = 'salmon';

If you need to add a class to the body element, use the classList.add method.

Copied!
document.body.classList.add('bg-salmon');

We passed an empty dependencies array to the useEffect hook because we only want to set styles on the body element once — when the component mounts.

If you need to remove the styles when the component unmounts, return a cleanup function from the useEffect hook.

Copied!
useEffect(() => document.body.style.backgroundColor = 'salmon'; return () => // 👇️ optionally remove styles when component unmounts document.body.style.backgroundColor = null; >; >, []);

To remove a style, you can just set it to null .

# Set styles on the Body element when an event is triggered

You can also set classes to the body element when an event is triggered, e.g. a button is clicked.

Copied!
export default function App() const handleClick = () => document.body.style.backgroundColor = 'salmon'; document.body.style.color = 'white'; >; return ( div> button onClick=handleClick>>Clickbutton> div> ); >

We set the onClick prop on the button element, so every time it is clicked, the handleClick function gets invoked.

# Toggle styles on the Body element when an event is triggered

If you need to toggle styles on the body element when an event occurs, conditionally check if the styles are already present and remove them if they are, otherwise, set the styles.

Copied!
export default function App() const handleClick = () => if (document.body.style.backgroundColor) document.body.style.backgroundColor = null; document.body.style.color = null; > else document.body.style.backgroundColor = 'salmon'; document.body.style.color = 'white'; > >; return ( div> button onClick=handleClick>>bobbyhadz.combutton> div> ); >

If the backgroundColor style is already set on the body element, we remove it by setting it to null , otherwise, we set it to salmon .

If you need to change a button’s text on click, check out the following article.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  The chosen index php
Оцените статью