0

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.

jobechoi
  • 69
  • 6
  • 3
    when you do: `this.state.currentSize++` you mutate the state directly. You should not mutate it. return `this.state.currentSize + 1`. Then if updating the state you need the prevstate, use the `this.setState(prevState => ({}))` – quirimmo Dec 25 '18 at 06:30
  • That's just precious. I'll need to look into that to see what other implications are shadowing about. prevState looks interesting. Thanks! – jobechoi Dec 25 '18 at 06:34
  • Possible duplicate of [When to use React setState callback](https://stackoverflow.com/questions/42038590/when-to-use-react-setstate-callback) – Shoaib Khan Dec 25 '18 at 06:50

2 Answers2

3

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!

Aamin Khan
  • 712
  • 4
  • 12
0

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

Thanks

Sahil Arora
  • 491
  • 3
  • 10