2

Is it possible to create state without using an object inside the constructor?

I need to dynamically create new states inside the component on the fly. Any recommendations?

Harris Lee
  • 93
  • 1
  • 2
  • 7
  • I didn't get the purpose of creating dynamic state. You can have empty state object in constructor and then manipulate the state object inside the component in any way you want. Can you elaborate your requirement here? – Umesh Jul 27 '17 at 04:22

4 Answers4

1

The state object is literally just a Javascript object, so it is already dynamic.

If you want, you can modify it anywhere, anytime. But this completely breaks the good design pattern that React gives you -- single source of truth for data, and no mutating any state objects gives you a perfect history of every action that has taken place, making debugging a piece of cake.

This is why they encourage you to create an initial state, then use setState, which just creates a new copy while modifying the fields you specified.

Skip down to 'Using State Correctly': https://facebook.github.io/react/docs/state-and-lifecycle.html

If you need to 'dynamically create new states on the fly', is there any reason you can't define these in the constructor with initial values, whether or not you use them? I don't see any reason they would have to not exist at first, instead of just have an initial state. More detail about what you're trying to do would be helpful.

Adam
  • 877
  • 2
  • 10
  • 24
  • Does that mean that if I am in a iterator, at that time can I create a state for the same? – Jimit Patel May 24 '18 at 13:34
  • 2
    Ok I found the solution I was looking for. Thanks, your answer enhanced my search skills :) (https://stackoverflow.com/a/29281499/842607) – Jimit Patel May 24 '18 at 13:38
0

in case you was using typescript, i would define your state like this:

interface IComponentState {
    dynamicState: any
}

and then you can assing any object to this dynamicState.... or any number of options to it...

in plain JS you even do not need to assign type, so it will be simplier - just assign empty object at start

Lojka
  • 167
  • 8
0

Create state in inner method - render, is bad idea.
React recommended use only setState(), or 'state = ...' in constructor.

0

If the key (string) of the new state element is stored in variable newKey, you can use

this.setState({ [newKey] : "new value" });

to dynamically add state.

I have found this useful when rendering a page based on a template where we don't know the elements to be rendered (and their state variable requirements) ahead of time.

Kahitarich
  • 395
  • 2
  • 7