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

2
  • stackoverflow.com/questions/29979324/… Commented Feb 5, 2018 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. Commented Feb 5, 2018 at 11:11

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

This would display both styles from highlightStyle and hoverStyle.

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

Comments

0
style={this.state.color_black ? highlightStyle : (this.state.hover ? hoverStyle: '')}

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.