D.S
D.S

Reputation: 105

Reactjs switching between components

I have 3 components that I render in my react app

previously I was rendering them using state

state = {
    one: true,
    two: false,
    three: false
}

rendering the one that I want by setting its state to true and all of the others to false

and rendering them

 <div>
      {
        this.state.one &&
        <Start
            switchDisplay={ this.switchDisplay }
            quizname={ quizname }
            author={ author }
        />
      }
      {  this.state.two &&
         <Playground
             {...this.state.currentQuestion}
             onclick={this.nextQuestion}
         />
      }
       {
         this.state.three &&
         <Score nominator={this.result} denominator={entry.length}/>
       }
    </div>

(dont mind the props for the moment)

later on I used a third party package

https://www.npmjs.com/package/react-display-name

now after refactoring a lil bit.

I have only one state which has the component as its value

and if I ever need to switch between the components I just change the state of it

and to pass in props I used this third party package

to get the current component name and some conditional logic to pass in the props

my question is which is the better approach

having all the components in state and setting the value to true and all the others to false.

or

having one state for the component directly passed in as its value.

and using 'third party package' to get the display name of the component currently rendered in and passing in the props using the name of the component.

more state or one extra package?

Upvotes: 0

Views: 460

Answers (1)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38922

Reducing work done to reconcile state changes is always a winning approach here. Therefore the better approach is having one state for the component directly passed in as its value.

You may not require an external library for this if only one of the 3 components is displayed per time.

In constructor()

const state = {
  display: 'start',
};

this.state = state;

Wire a lookup object for all 3 components with object keys as possible state values

const gameComponentRegistry = {
  'start': Start,
  'playground': Playground,
  'score': Score,
}

export default gameComponentRegistry;

In render(), import and lookup component to render in gameComponentRegistry

const component = gameComponentRegistry[this.state.display];
const props = {}; // makeup props
<div>
  { <component ...props /> }
</div>

Upvotes: 3

Related Questions