N
N
Nikolai Antonov2016-08-20 10:45:40
JavaScript
Nikolai Antonov, 2016-08-20 10:45:40

How to set props value dynamically?

There is a dynamicData variable that changes every 3 seconds. How to set the value of the variable in props or in another way so that the component is automatically rendered when it changes? Code jsfiddle.net/jv69s81h/4/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nemiro, 2016-08-20
@my-nickname

Use state instead of props :

var Hello = React.createClass({
  getInitialState: function() {
    return { test: 0 };
  },
  componentWillMount: function() {
    setInterval(() => {
      var dynamicData = (Math.random() * 100).toFixed(0);
      this.setState({ test: dynamicData });
    }, 3000);  
  },
  render: function() {
    return <h2>{this.state.test}</h2>;
  }
});

ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);

If props are needed , then the parent component can change the state and pass it to the desired property of the child component, and the child component can handle the changes in componentWillReceiveProps(nextProps) .
You can also call forceUpdate() , but it's best not to.
It is better to refuse idea of ​​external control of components at once. There will be fewer problems. Everything should be inside the components, or not related to the components at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question