Search code examples
reactjsreact-routerreloadreact-dombrowser-refresh

Invariant Violation: Objects are not valid as a React child. Check the render method of `Content`


I am getting the above error once I am refreshing the page and reloading the same props by getting it from the state.I am not able to find why is it happening while reload of page , on first load page is loading fine.

  const Content = (props) => {
      if (props.tabItem.contentList !== undefined) {
        return (
          <div>
            {props.tabItem.contentList.map((tab) => {
              if (props.tabItem.currentTab === tab.tabId) {
                return (
                  <div key={props.tabItem.currentTab}>
                    {tab.content.props.children}
                  </div>
                );
              }
            })}
          </div>
        );
      }
      return (
        <div>no record</div>
      );
    };

My tabItem that saving in the state is like this:-

 tabList = [{
        tabId: '1',
        tabName: 'Test'
        isPrimary: true,
      },
      ];
      // create new contentList
      contentList = [
        {
          tabId: '1',
          content: <div> <Test1Container{...this.props} addTab={this.addTab} /></div>,
        },
      ];
      tabData = {
        tabList,
        currentTab: '1',
        contentList,
      };
this.props.addTabItem(tabData);
this.props.addTabItem is use to save the state.

Solution

  • Changes:

    1. Write an else condition, if if condition fails then in that case component is not returning anything.

    2. We can't use if/else inside jsx so use ternary operator for conditional rendering.

    3. currentTab is present inside tabData so write it like this to access it's value:

    props.tabItem.currentTab
    

    4. Return null if condition fails inside map body.

    Use this:

    const Content = (props) => {
      if (props.tabItem.contentList !== undefined) {
        return (
          <div>
             {props.tabItem.contentList.map((tab) => {
                return props.tabItem.tabData.currentTab === tab.tabId ? 
                     <div key={props.tabItem.currentTab}>
                         {tab.content.props.children}
                      </div>
                      : null
             })}
          </div>
        )
      }else{
          return null
      }
    }
    

    Check this sample working snippet:

    var a = <div><p>hello</p><p>world</p></div>
    
    var App = (props) => {
        return <div>{props.a.props.children}</div>
    }
    
    ReactDOM.render(<App a={a}/>, document.getElementById('app'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    
    <div id='app'/>