Reputation: 3605
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.
Upvotes: 0
Views: 328
Reputation: 18831
{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
Upvotes: 1
Reputation: 443
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'));
Upvotes: 1