'how to add dynamic css in react js
can we achieve this in React js style={style} ??
constructor(props) {
super(props);
this.state = {
style_title: {"color": "blue"}
};
this.change = this.change.bind(this);
}
change(e) {
this.setState({
[e.target.name]: e.target.value })
}
My Form:
<input type="text" name="title" value={this.props.title} onChange={e =>this.changeEdit(e)} />
<input type="text" name="style_title" value={this.props.style_title} onChange={e =>this.changeEdit(e)} />
title text print on preview mode for this I need to styles title dynamically using input field for ex:
{ "color": "blue", "font-size": "22px",}
above styles should apply render <p style={style}>{this.props.title }</p> in style attribute
Preview Section:
render = () => (
const style = this.props.style_title;
return (
<p style={style}>{this.props.title }</p>
);
)
Solution 1:[1]
In React you can pass dynamic style either by passing object as mentioned here:
React.js inline style best practices
Or you can also pass inline like:
<div style={{ height: '10%' }}>
Hello World!
</div>
One note though, the css properties will be in camelCase, e.g. borderBottom: '10px'
Solution 2:[2]
One of the way to change styles in react, is by using ternary operators.
<div className={3>2 ? "red" : "black"} >
// write your code here
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nah |
| Solution 2 |

