- Create Components folder under src folder
- Add SettingClassNamesDynamically.js file and add below Code
import React, { Component } from 'react';
import './SettingClassNamesDynamically.css';
class SettingClassNamesDynamically extends Component {
state={
myCount:3
}
render () {
const classes=[];
if(this.state.myCount===1)
{
classes.push('red');
}
else
if(this.state.myCount===2)
{
classes.push('red');
classes.push('bold');
}
else
if(this.state.myCount===3)
{
classes.push('red');
classes.push('bold');
classes.push('backColor');
}
return (
<div>
<h1>Setting Class Names Dynamically</h1>
<p className={classes.join(' ')}>Here is my test data, Based on count style will change</p>
</div>
);
}
}
export default SettingClassNamesDynamically;
- Add SettingClassNamesDynamically.css file and add below Code
.red {
color:red;
}
.bold {
font-weight:bold;
}
.backColor{
background-color:green;
}
- Open App.js file and update code as below\
import React from 'react';
import './App.css';
import SettingClassNamesDynamically from './Components/SettingClassNamesDynamically'
function App() {
return (
<div className="App">
<SettingClassNamesDynamically/>
</div>
);
}
export default App;
Output:
If myCount=1
If myCount=2
If myCount=3
No comments:
Post a Comment