Add a State property to an Inline Style in React

15,739

Solution 1

You can do it like this

style={ { width: `${ this.state.percentage }%` } }

Example

Solution 2

yes its possible check below

class App extends React.Component {

  constructor(props){
    super(props)
    this.state = {
      width:30; //default
    };
  }


  render(){

//when state changes the width changes
const style = {
  width: this.state.width
}

  return(
    <div>
    //when button is clicked the style value of width increases
      <button onClick={() => this.setState({width + 1})}></button>
      <div className='progress-bar'
           role='progressbar'
           style={style}>
      </div>
    </div>
  );
}

:-)

Share:
15,739
lost9123193
Author by

lost9123193

Learning

Updated on June 16, 2022

Comments

  • lost9123193
    lost9123193 almost 2 years

    I have a react element that has an inline style like this: (Shortened version)

          <div className='progress-bar'
               role='progressbar'
               style={{width: '30%'}}>
          </div>
    

    I want to replace the width with a property from my state, although I'm not quite sure how to do it.

    I tried:

          <div className='progress-bar'
               role='progressbar'
               style={{{width: this.state.percentage}}}>
          </div>
    

    Is this even possible?

  • stackdave
    stackdave over 6 years
    do you use a tool to add the semicolons automatically?
  • Muhammed Moussa
    Muhammed Moussa about 3 years
    you can set up eslint on save in vscode to do that