jobechoi
jobechoi

Reputation: 69

React component only updating once

New to React and finding it exciting and overwhelming.

I have the following code. I'm trying to increment the font size using a state within the component, and then render the updates to the web page with a bit of text.

constructor(props) {
		super(props);
		this.state = {
			maxSize: this.props.max,
			currentSize: this.props.size
};

iSizeClick() {
  this.setState({ currentSize: this.state.currentSize < this.state.maxSize ? this.state.currentSize++ : this.state.currentSize });
}

render() {
  var size = this.state.currentSize;
    	  	
  return(		
	  <div>
	    <span id="fontSizeSpan" hidden={this.state.hidden}>{size}</span>
	    <button id="increaseButton" hidden={this.state.hidden} onClick={this.iSizeClick.bind(this)}>+</button>
	    <span id="textSpan" onClick={this.handleClick.bind(this)} style={{fontWeight:bold, fontSize:size}}>{this.props.text}</span>
	  </div>
  );
}

I'm failing to see what is limiting my ability to get the component to render with each click of the increment button.

Upvotes: 0

Views: 171

Answers (2)

Sahil Arora
Sahil Arora

Reputation: 491

As per my observationo kindly make following changes to your code:-fontWeight: size + 'px'.

Thanks

Upvotes: 0

Aamin Khan
Aamin Khan

Reputation: 722

Pass prevState to the setState

iSizeClick() {
    this.setState(prevState => ({
      currentSize:
        prevState.currentSize < prevState.maxSize
          ? prevState.currentSize + 1
          : prevState.currentSize
    }));
  }

Here is my code sandbox https://codesandbox.io/s/j343ww1v03 Cheers!

Upvotes: 3

Related Questions