Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use componentDidMount variables from event functions

Im trying to access a variable created in the componentDidMount method. Whats the best way to do it?

componentDidMount() {
    var x = "hello";
}

bye() {
    x = "bye";
}

render(){
    return (<div onClick={this.bye}>)
}
like image 229
Miguel Morujão Avatar asked Dec 08 '25 14:12

Miguel Morujão


1 Answers

Use React's state for this:

class Example extends React.Component {
  constructor() {
    super();
    this.state = { x: "" };
    this.bye = this.bye.bind(this);
  }
  
  componentDidMount() {
    this.setState({ x: "hello" });
  }

  bye() {
    this.setState({ x: "bye" });
  }

  render(){
    return (<div onClick={this.bye}>{this.state.x}</div>)
  }
}

ReactDOM.render(<Example/>, document.getElementById('View'));
<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="View"></div>
like image 73
Fabian Schultz Avatar answered Dec 11 '25 03:12

Fabian Schultz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!