6

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

user264675
  • 356
  • 1
  • 6
  • 19
  • Possible duplication of : https://stackoverflow.com/questions/26882177/react-js-inline-style-best-practices – Nah May 10 '18 at 12:45
  • your question need to explain more that you wrote, your desire is a little unclear, Do you mean, you wanna have a form to get the style and implement it to another component? – AmerllicA May 10 '18 at 13:12
  • yes , once I click submit value should updated this.state {title:"",custom_css:""} – user264675 May 10 '18 at 13:34

2 Answers2

4

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'

Nah
  • 1,690
  • 2
  • 26
  • 46
  • I need to add custom css as user input form fields to style text – user264675 May 10 '18 at 13:00
  • In that case, you will need to save the form input value to your component `state` as an object. And then in your `render()` method you need to or should be using the `state` values in desired area/place like `this.state.myStyleProp1`, etc. – Nah May 10 '18 at 13:04
  • Yes, but only if `style_title` holds the object and **not** just string value. e.g. `this.state = {style_title: {height: '20px', width: '90px'}}` So then you can use it the way you mentioned. – Nah May 11 '18 at 01:25
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>