ReactJs: How to pass the initial state while rendering a component?
If you know the state then I would tend to argue that the component you are rendering is not really in control of it. The idea in React is that any particular piece of state lives in only a single location.
To quote the React docs:
Using props, passed down from parent, to generate state in
getInitialState
often leads to duplication of "source of truth", i.e. where the real data is. Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble
And:
However, it's not an anti-pattern if you make it clear that synchronization's not the goal here
So if your props include a value
and an initialValue
, then it's clear that the latter is for initialization, and there's no confusion.
See the React docs for code examples.
Disclaimer: Newer versions of React handle this on a different way.
Only permanent components might be able to use props in the getInitialState
. Props in getInitialState
is an anti-pattern if synchronization is your goal. getInitialState
is only called when the component is first created so it may raise some bugs because the source of truth is not unique. Check this answer.
Quoting documentation:
Using props, passed down from parent, to generate state in getInitialState often leads to duplication of "source of truth", i.e. where the real data is. Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble
You can still do:
getInitialState: function() {
return {foo: this.props.foo}
}
As they will be the default props for your app. But as long as you are using a prop to set a value that presumably won't change, you can use the same prop inside of the render
function.
<span>{this.props.foo}</span>
This props won't be modified, so no problem using it each time the render
is called.
Edited answer:
In this case your initial state should not be a prop, should be an ajax call which populates the comment list.