andrerpena andrerpena - 1 month ago 5
Javascript Question

ReactJs: How to pass the initial state while rendering a component?

I know I can pass

props
while rendering a component. I'm also aware of the
getInitialState
method. But the problem is,
getInitialState
isn't quite helping because my component doesn't know it's initial state. I do. So I want to pass it while I'm rendering it.

Something like this (pseudo-code):

React.render(<Component initialState={...} />);


I know I could use a
prop
to work as the initial state but this smells like an anti-pattern.

What should I do?

EDIT FOR CLARITY

Imagine I have a
CommentList
component. By the time I first render it, the initial state corresponds to the snapshot of current comments from my database. As the user includes comments, this list will change, and that's why it should be a
state
and not
props
. Now, in order to render the initial snapshot of comments I should pass it to the
CommentsList
component, because it has no way to know it. My confusion is that the only way I see to pass this information is through a
props
which seems to be an anti-pattern.

Answer

Only permanent components might be able to use props in the getInitialState. Props in getInitialState is an anti-pattern. getInitialState is only called when the component is first created so it may raise some bugs.

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.prop.initialfoo}</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.

Comments