Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add dynamic css in react js

Tags:

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>
 );
)

My form look this with preview mode

like image 688
user264675 Avatar asked May 10 '18 12:05

user264675


2 Answers

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'

like image 154
Nah Avatar answered Sep 28 '22 19:09

Nah


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>
like image 24
Manas Mishra Avatar answered Sep 28 '22 18:09

Manas Mishra