When it comes to handling inline styles, there are two scenarios to consider. Which approach is the most effective for 'toggling' CSS properties based on the component state - or is there a better alternative?
1. The first method involves creating a style variable where you check the component's state to determine the styling. This approach utilizes only one object when assigning the style in your JSX. You can see it in action here. Interestingly, this method is not discussed in this popular question thread.
render() {
const style = {
pStyle: {
borderRadius: this.state.isCircle ? '50%' : '0px', // Check current state
height: this.state.isCircle ? '100px' : 'auto', // Check current state
display: 'inline-block',
width: '100px',
textAlign: 'center',
transition: 'all 0.5s ease-in-out',
border: 'solid 2px lightblue'
}
}
return (
<div>
<p style={style.pStyle} onClick={this.HandleClick}>Hi!</p>
</div>
)
}
2. The second method involves creating multiple objects to represent each CSS state of the component. In this case, you need to check the component's state in your JSX and merge the objects using ES6's Object.assign. See it working here.
render(){
const style = {
pStyle : {
display: 'inline-block',
width: '100px',
textAlign: 'center',
transition: 'all 0.5s ease-in-out',
border: 'solid 2px lightblue'
},
pStyleCircle : { // This will only be applied when the state is Circle
borderRadius: '50%',
height: '100px',
}
}
return (
<div>
<p style={Object.assign({}, style.pStyle, this.state.isCircle && style.pStyleCircle)} onClick={this.HandleClick}>Hi!</p>
</div>
)
}
Both approaches are functional, but which one is preferable and why?