0

I want to render two completely separate components based on whether the user is logged in or not. This is my code,

import React, {Component} from 'react';
import ContainerLogged from './components/logged/ContainerLogged'
import ContainerUnlogged from './components/unlogged/ContainerUnlogged'

class App extends Component {
    constructor(props){
        super(props)
        this.state = {isLoggedIn : false}
    }
    render(){
        const comp = this.state.isLoggedIn ? (
            <ContainerLogged />
        ): (
            <ContainerUnlogged />
        );
        return (

            {comp}
        );
    }
}
export default App;

This is my index.js

import 'normalize.css';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

I get the following error,

Objects are not valid as a React child (found: object with keys {comp}). If you meant to render a collection of children, use an array instead.
    in App (at index.js:8)

I'm new to React and thus dont understand what's going on over here.

1
  • comp itself is a react child, simply return that. Commented May 12, 2018 at 21:21

3 Answers 3

2

Instead of

return (

    {comp}
);

try

return comp;
Sign up to request clarification or add additional context in comments.

Comments

1

You are in right direction, I would suggest to break your render function, it always helps when you have conditional logic.

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends Component {
  constructor() {
    super();
    this.state = {
      isLoggedIn: false
    };
  }

  renderLoggedIn = () => {
    return (
      <div>
        <h2>Logged In</h2>
      </div>
    );
  }
  renderNotLoggedIn = () => {
    return (
      <div>
        <h2>Not Logged In</h2>
      </div>
    );
  }
  render() {
    let element = null;
    if (this.state.isLoggedIn) {
      element = this.renderLoggedIn();
    } else {
      element = this.renderNotLoggedIn();
    }
    return element;
  }
}

render(<App />, document.getElementById('root'));

Comments

1

{comp} is an object with key comp and value the value of the variable comp. That does make much sense here. (That's ES2015 "Shorthand property names" feature)

You must simply return comp instead of an object: return comp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.