Ad

Conditional With Multiple React Components In Class Render Method

- 1 answer

I have a React class with a render method that includes 1 or 3 child components.

If the user is logged out, only the first component should be rendered, and if the user is logged in (or when the user logs in) the second two should also be rendered.

render() {
    return (
        <div className="lists-wrapper {this.data.user}">
            <List title="Featured" tiles={this.data.featured} />
            { this.data.user ?
                <List title="Faves" tiles={this.data.faves} />
                <List title="My Content" tiles={this.data.owned} />
            }
        </div>
    );
}

However I get the following error:

Adjacent JSX elements must be wrapped in an enclosing tag (58:5)

I can find plenty of documentation and examples of conditionally including one component or another, but nothing which helps me in this use-case. Without the conditional, and adding all three of them works as expected.

Ad

Answer

You should wrap adjacent JSX elements in another element, like div.

Moreover, I will suggest to move the rendering logic to another function to make it clear.

/*
 * A simple React component
 */
class List extends React.Component {
  render() {
    return <b>{this.props.title}</b>;
  }
}

class Application extends React.Component {
  renderSection(flag) {
      if(flag) {
        return (<div><List title="Faves"/>
              <List title="My Content"/>
                </div>);  
      }
    }
  render() {
    return (
        <div className="lists-wrapper">
            <List title="Featured" />
            { 
              this.renderSection(true)
            }
        </div>
    );
  }
}

/*
 * Render the above component into the div#app
 */
React.render(<Application />, document.getElementById('app'));
Ad
source: stackoverflow.com
Ad