Summary
When you add dynamic css react in the traditional way is more complicated today, just learning to a library module can easily solve this problem. Right, it is "classnames".
classnames module library
npm install
npm install classnames --save
Usage with React.js
classnames function takes any number of class parameters, these parameters may be a string or class objects, class parameter with a given true || false pattern class to dynamically increase or decrease. The following shows a simple dynamic style class Click the class to explain the basic usage of classnames. Click event with fast rendering of state React hooks, in order to better display in this case, taken at the time of setSatte! Click achieve state font color rendering cycle way.
App.js Code
import React, { useState } from 'react'
import './App.less'
import classnames from 'classnames'
const App = () => {
const [clickStatus,setClickStatus] = useState(false);
const boxClick = () =>{
setClickStatus(!clickStatus);
};
return (
<div className='box'>
<div
className={classnames({
'box-content': true,
'box-content-color': clickStatus,
})}
onClick={boxClick}
>
Hello,Jack!
</div>
</div>
);
}
export default App;
App.less Code
/ * {App less style assembly} * /
.box {
width: 100vw;
height: 30vh;
.unity();
flex-direction: column;
}
/ * Pass a less pattern {} * /
.unity{
display: flex;
justify-content: center;
align-items: center;
}
/ * Content- static style * /
.box-content{
background: #33a579;
margin-top: 20px;
color: black;
font-size: 3vmin;
font-weight: 700;
border-radius: 1vmin;
cursor: default;
}
/ * Content- dynamic style * /
.box-content-color{
color: gold;
}
Test Results
to sum up
Share the actual project in a very practical classnames module library can be simple and quick to implement dynamic changes in style.