Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass event to setState callback function?

Is it possible in React to pass an external event to the callback function of setState?

Example

someFunc(event) { 
    this.setState(
        {
            value: event.target.value
        },
        () => {                 
            this.props.onChange(event);    // <- cannot pass to here                
        }
    );
}

EDIT: See accepted solution below by Liam for an excellent answer, Here is the specific solution to my problem:

Solution

someFunc(event) { 
    event.persist() // <- add this line and event should pass without a problem
    this.setState(
        {
            value: event.target.value
        },
        () => {                 
            this.props.onChange(event);                 
        }
    );
}
like image 235
Frederik Petersen Avatar asked Jun 12 '18 21:06

Frederik Petersen


1 Answers

You need to extract the values or use e.persist()

https://reactjs.org/docs/events.html#event-pooling

class App extends React.Component {

something = (value) =>{
  {console.log(value, 'coming from child')}
}
  render() {

    return (
      <div >
        <Hello text={this.something} />
      </div>
    );
  }
}


class Hello extends React.Component {

  constructor() {
    super()
    this.state = {
      value: ''
    }
  }
  onChange = (e) => {
    const value = e.target.value;
    this.setState({ value }, () => {
    
      this.props.text(value)
    })
  }
  render() {

    return (
      <div style={{ padding: 24 }}>
        <input onChange={this.onChange} value={this.state.value} />

      </div>
    );
  }
}



ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='root' ></div>

Or if you meant to pass the value state you can use this.state.value in callback it will work.

someFunc(event) { 
    this.setState(
        {
            value: event.target.value
        },
        () => {                 
            this.props.onChange(this.state.value);    // <- this should work                
        }
    );
}
like image 181
Liam Avatar answered Sep 18 '22 16:09

Liam