Reputation: 89
I wanna know how to use multiple independent conditional styles on same div in react js. For one condition we can use ternary operator. But i want to use different independent conditions.
For example: I have a textarea and I have three buttons with Bold, italic and underline. I want if i click on any button will do their respective task.
this is working fine
<textarea
onChange={this.handleChange}
style={ this.state.bold ? {fontWeight: 'bolder'} : {fontStyle:
'normal'}}
/>
but this is not:
<textarea
onChange={this.handleChange}
style={ this.state.bold ? {fontWeight: 'bolder'} : {fontWeight:
'normal'}}
style={ this.state.italic? {fontStyle: 'italic'} : {fontStyle:
'normal'}}
/>
How to have multiple independent conditional styles in reactjs?
Upvotes: 3
Views: 6835
Reputation: 61
You can make this:
const handleStyleButton = (condition) => {
if (condition) {
return {
backgroundColor: 'pink',
height: 40,
borderRadius: 10,
border: 'none',
margin: '.5em',
minWidth: 60,
cursor: 'pointer'
}
}
return {
backgroundColor: '#fff',
height: 40,
borderRadius: 10,
border: 'none',
margin: '.5em',
minWidth: 60,
cursor: 'pointer'
}
};
with html
<button style={handleStyleButton(true)} />
Upvotes: 5
Reputation: 2361
You can't add two styles to one div.Maybe not a good choice, you can use both style and className:
style={ this.state.bold ? {fontWeight: 'bolder'} : {fontWeight:
'normal'}}
className={ this.state.italic? {fontStyle: 'italic'} : {fontStyle:
'normal'}}
And you can also try this:
setStyle (){
let styles = {}
if (this.state.first === 'first'){
const firstStyle = {
...
}
styles = Object.assign(styles,firstStyle)
}
if (this.state.second === 'second'){
const secondStyle = {
...
}
styles = Object.assign(styles,secondStyle)
}
if (this.state.third === 'third'){
const thirdStyle = {
...
}
styles = Object.assign(styles,thirdStyle)
}
return styles
}
....
<div style={this.setStyle()}>Test</div>
Upvotes: 2
Reputation: 11
in css.
<style>
.class1{
}
.class2
{
}
</style>
in react use those classes based on the condition and use nested it if you want
.store the class in state
{this.state.case1?class1:class2}
Upvotes: 0
Reputation: 11770
You can nest ternaries.
Note that this can get pretty unreadable super fast.
style={
this.state.bold
? this.state.italic
? { fontWeight: "bolder", fontStyle: "italic" }
: { fontWeight: "bolder", fontStyle: "normal" }
: this.state.italic
? { fontWeight: "normal", fontStyle: "italic" }
: { fontWeight: "normal", fontStyle: "normal" }
}
Upvotes: 2