How to make dynamic style or class in react?
How to add dynamic style in the react: yes we can do need to use trick javascript push method with if conditions. Also add style as using on the button, as below code you can see:
App.js
import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';
class App extends Component {
state = {
persons: [
{ name: 'Sheo', age: 38 },
{ name: 'Raj', age: 33 },
{ name: 'Sagar', age: 55 }
],
otherStates: 'Some other value',
showPersons: false,
}
toggleHandler = () => {
const doesShow = this.state.showPersons;
this.setState({ showPersons: !doesShow })
}
switchNameHandler = () => {
//console.log('Was clicked')
this.setState({
persons: [
{ name: 'Sheo Sagar', age: 38 },
{ name: 'Raj', age: 33 },
{ name: 'Mahesh Kumar', age: 23 }
]
})
}
nameChangedHandler = (event) => {
this.setState({
persons: [
{ id: 'fnaes', name: 'Sheo Sagar', age: 38 },
{ id: 'fnaesfs', name: event.target.value, age: 33 },
{ id: 'asdf', name: 'Mahesh Kumar', age: 23 }
]
})
}
deleteHandler = (personIndex) => {
const persons = [...this.state.persons];
persons.splice(personIndex, 1);
this.setState({ persons: persons })
}
render() {
const style = {
border: '2px solid #ccc',
backgroundColor: '#0bf',
padding: '15px',
color: '#fff'
}
let person = null;
if (this.state.showPersons) {
person = (
<div>
{this.state.persons.map((item, per) => {
return <Person name={item.name}
age={item.age}
click={() => this.deleteHandler(per)}/>
})}
</div>
)
style.backgroundColor = '#f00';
}
const styless = [];
if(this.state.persons.length <=2){
styless.push('red');
}
if(this.state.persons.length <=1){
styless.push('bold');
}
return (
<div className="App">
<h1>How to make dynamic style or class in react</h1>
<p className={styless.join(' ')}>It's really working!</p>
<button onClick={this.toggleHandler} style={style}>Toggle Switch</button>
{person}
</div>
)
};
}
export default App;
Person.js
import React from 'react';
import './Person.css';
const person = (props) => {
return (
<div className="person" onClick={props.click}>
<p>I am {props.name} I am {props.age} years old.</p>
<p>{props.children}</p>
<div><input type="text" onChange={props.changed} /></div>
</div>
)
}
export default person;
Person.css
.person{max-width: 70%;
margin: 20px auto;
border: 1px solid #ccc;
padding: 20px;
}
.red {
color: #f00;
}
.bold {
font-weight: 700;
}
No comments:
Note: Only a member of this blog may post a comment.