James
James

Reputation: 3815

ReactJS Making Component state available outside Component definition

I am building a simple dashboard. I have a object dictionary (dashboardItems) holding dashboard items to show (either <SubComponent1 /> or <SubComponent 2/>, a helper function to return the component from the dictionary (getDashBoardContent()), and finally I have the dashboard component (<DashBoard />). I am passing a prop to <SubComponent 2/> by means of a simple state, optionId:

const dashboardItems = [
  {
    id: 0,
    content: <SubComponent1 />
  },
  {
    id: 1,
    content: <SubComponent2 options={this.state.optionId} />
  }
];

const getDashBoardContent = listItemIndex => {
  return dashboardItems[listItemIndex].content;
};

class DashBoard extends Component {
  state = {
    listItemIndex: 0,
    optionId: 0,
  };

  handleClick = (item, id) => {
    this.setState({
      listItemIndex: item,
      optionId: id,
    });
  };

  render() {
    return
    ...

The problem is that React is throwing an error that it cannot read the property options={this.state.optionId}. I am assuming that the reason is that the dictionary dashboardItems is outside the Dashboard component that is defining the state.

What strategies should I use?

(Note: although I am using Redux in my application, I do not want to use it just to track the item to display in the dashboard).

Upvotes: 0

Views: 46

Answers (2)

Nikita Tsyhanenko
Nikita Tsyhanenko

Reputation: 1

You can wrap your components in dashboard list into functions like this:

const dashboardItems = [
  {
    id: 0,
    content: () => <SubComponent1 />
  },
  {
    id: 1,
    content: (state) => <SubComponent2 options={state.optionId} />
  }
];

class DashBoard extends Component {
   ...

   render() {
     const item = dashboardItems.find(x => x.id === this.state.listItemIndex);

     return (
       <div>
         {item.content(this.state)}
       </div>    
     );
   }
}

Upvotes: 0

Waweru Mwaura
Waweru Mwaura

Reputation: 257

Rather than using the function to set and initialize the components do you mind using the React conditional rendering property such as this:

class DashBoard extends Component {
  state = {
    listItemIndex: 0,
    optionId: 0,
  };

  handleClick = (item, id) => {
    this.setState({
      listItemIndex: item,
      optionId: id,
    });
  };

  render() {
  {listItemIndex, optionid} = this.state
    return ()
    {if desired state: <SubComponent1 /> : 
 <SubComponent2 options={this.state.optionId} />
//If desired state render component one else render the other component 
    ...
}

Upvotes: 1

Related Questions