Joff
Joff

Reputation: 12197

reactJS how to change between many application states

New to reactJS and I am trying to have one of my components alternate through many CRUD states (creating object, listing objects, updating objects, deleting objects), each one will display appropriate forms...

I was thinking to do it like this but I cannot see if my thinking is flawed.

constructor() {
    super(props);

    this.state = {
        list: true,
        edit: false,
        create: false,
        // and so on for CRUD operations
}

then later there would be a method...

handleCRUDViewChange(newView) {
    // flip everything to false...
    // turn the correct one to true
}

then in the render would be something like this...

switch (true) {
case this.state.list:
    <ListComponent />
case this.state.edit:
    <EditComponent />
// and so on...
}

Is my thinking sound? Is this the "react" way to do things?

Upvotes: 0

Views: 44

Answers (2)

Gautham Kumaran
Gautham Kumaran

Reputation: 441

There is no need to maintain a seperate state variable, for each crud view. The code can be simplified as

constructor() {
super(props);
this.state = {
      crudView : 'list'
     }
}

handleCRUDViewChange(newView) {
this.setState({
     crudView : newView
   })    
}

The conditional rendering must also be changed accordingly

switch(this.state.crudView) {
case 'list':
     <ListComponent/>
case 'edit':
     <EditComponent/>
//and so on
}

Upvotes: 1

hazardous
hazardous

Reputation: 10837

Yes, you are on the right track. You may want to simplify this a bit -

const MODES = {LIST: 0, EDIT: 1, CREATE: 2},
CRUD_COMPONENTS = [ListComponent, EditComponent, CreateComponent];
constructor(){
    this.state = {"mode" : MODES.LIST};
},
handleCRUDViewChange(newView) {
   // decide the relevantMode value out of LIST, EDIT or CREATE based on your logic
   // and then update state
   this.setState({"mode": MODES[relevantMode]});
}
render(){
   let Component = CRUD_COMPONENTS[this.state.mode];
   return <Component />;
}

In your simple example, you are not having to send CRUD mode specific state to the component, while in the real case, you may have to write some more logic to store mode-specific props and pass them to the selected mode component.

Upvotes: 1

Related Questions