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.
-
comp itself is a react child, simply return that.AjayK– AjayK2018年05月12日 21:21:51 +00:00Commented May 12, 2018 at 21:21
3 Answers 3
Instead of
return (
{comp}
);
try
return comp;
Comments
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
{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