0

Here I want to use two style in one line css. but i got error how i add two style object in style tag reactjs. here is my code:

const style = {
    color:"black",
    fontSize:16,
    borderRadius:4,
    border: "1px solid grey",
    lineHeight: "28px",
    background: "white",
    padding: 3,
    margin:3
  }
  const hoverStyle = {
    color:"black",
    fontSize:16,
    borderRadius:4,
    border: "1px solid grey",
    lineHeight: "28px",
    background: "yellow",
    padding: 3,
    margin:3
  }
const highlightStyle = {
    color:"black",
    fontSize:16,
    border: "1px solid grey",
    background:"lightblue",
    borderRadius:4,
    lineHeight: "25px",
    padding: 3,
    margin:5
  }

 onHover(){ 
        console.log("mouse enter")  
        // this.setState({hover:!this.state.hover})       
    }
 
 
 <span id={this.props.atId} className = {this.props.classword}
  style={this.state.color_black ? style: highlightStyle,this.state.hover ? hoverStyle: ''}
  onClick={this.changeColor}
  onMouseEnter={() => {this.onHover()}}
  onMouseLeave={() => {this.onUnHover()}}
  //
>
  {item}
</span>
so what should i do add two style object in one line. here i am using ternary operator. if my condition is true then print true part. can anyone tell me how i add two style object. help will be appreciated. thank you
stackoverhelp
  • 61
  • 2
  • 3
  • 15
  • https://stackoverflow.com/questions/29979324/how-to-combine-multiple-inline-style-objects – Jigar Shah Feb 05 '18 at 10:59
  • your effort is apreciated. but i want to write this in one style tag look at this {this.state.color_black ? style: highlightStyle (I GOT ERROR HERE),this.state.hover ? hoverStyle: ''} ............ here i am using two ternary operator. – stackoverhelp Feb 05 '18 at 11:11

3 Answers3

1

style={{...highlightStyle , ...hoverStyle}}

This would display both styles from highlightStyle and hoverStyle.

The ... operator is called spread operator in es6. More on spread

illiteratewriter
  • 4,155
  • 1
  • 23
  • 44
1

change on applying styles :

style={Object.assign({},
        this.state.color_black ? style : highlightStyle,
        this.state.hover && hoverStyle)}
        onMouseOver={this.hoverOn}
        onMouseLeave={this.hoverOff}

Working demo below :

working demo

Jayavel
  • 3,377
  • 2
  • 21
  • 35
0
style={this.state.color_black ? highlightStyle : (this.state.hover ? hoverStyle: '')}
Rodius
  • 2,271
  • 14
  • 19
  • no no dont change my code actually this.state.colorblack is operator and this.state.hover both are ddifferent. so tell i i add two ternary operator in one style tag react – stackoverhelp Feb 05 '18 at 11:18