Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v4 - Error: React.Children.only expected to receive a single React element child

I'm using react router v4 in a very simple app. I've tried to follow the documentation but I have a weird error when my app try to launch.

The error says: error: React.Children.only expected to receive a single React element child

The weird thing is that I have only one component in my ReactDOM.render function.

Here's some snippets on my code:

index.js:

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

app.js (I hide all the obvious component imports):

import { BrowserRouter as Router, Route } from 'react-router-dom'

class App extends Component {
  render() {
    return (
      <Router>
        <div className="App">
          <Route path='/'>
            <Header/>
            <div className="search-container">
              <SearchBar/>
              <AddMovieButton/>
            </div>
            <SearchResultsList/>
          </Route>
          <Route exact path='/new'>
            <AddMovieForm/>
          </Route>
        </div>
      </Router>
    );
  }
}

export default App;

I can't really understand why this is not working, and why I have that error.

like image 824
Stan Amsellem Avatar asked May 28 '17 12:05

Stan Amsellem


1 Answers

You can have an only one child element inside a Route. If you want to have multiple, wrap them with a div as follows.

<Route path="/">
  <div>
    <Header />
    <div className="search-container">
      <SearchBar />
      <AddMovieButton />
    </div>
    <SearchResultsList />
  </div>
</Route>;
like image 172
Tharaka Wijebandara Avatar answered Nov 04 '22 10:11

Tharaka Wijebandara