-1

I have problem in React.js when I save the code the website page say:

A <Router> may have only one child element

What is the problem and how can I solve it?

import React, { Component } from 'react';
import Head from './component/head';
import Contacts from './component/contacts';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import Addcontacts from './component/Addcontacts';

import { Provider } from "./context";

import 'bootstrap/dist/css/bootstrap.min.css';

class App extends Component {
    render() {
        return (
            <Provider>
                <Router>
                    <Head promo = 'alow' />
                    <div className='container'>
                        <Switch>
                            <Route exact path='/' Component={Contacts} />
                            <Route exact path='/add' Component={Addcontacts} />
                        </Switch>
                    </div>
                </Router>
            </Provider>
        );
    }
}

export default App;
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Possible duplicate of [React-Router only one child](https://stackoverflow.com/questions/42992911/react-router-only-one-child) – evgeni fotia Oct 22 '18 at 15:27

3 Answers3

0

you can use React.Fragment https://reactjs.org/docs/fragments.html#short-syntax to fix this issue.

     <Router>
        <>
          <Head promo = 'alow' />
          <div className='container'>
            <Switch>
              <Route exact path='/' Component={Contacts} />
              <Route exact path='/add' Component={Addcontacts} />
            </Switch>
          </div>
       </>
     </Router>

So basically you just need to have a single tag in you compenent as a child.

Smolin Pavel
  • 501
  • 3
  • 8
0

Inside your <Router> wrap everything in a single <div> like this

<Router>
  <div>
  // all your content
  </div>
 </Router>
Josh
  • 20
  • 4
0

Router expect this.props.children to be null or to have length equal to 1

In your case its more than 1

So if you wrap all attr. inside a single tag it should work fine

You can use any of these

<> => React.Fragment
<div> => DIV

Eg:

class App extends Component {
      render() {
        return (
          <Provider>
            <Router>
                <div>
                  <Head promo = 'alow' />
                  <div className='container'>
                    <Switch>
                      <Route exact path='/' Component={Contacts} />
                      <Route exact path='/add' Component={Addcontacts} />
                    </Switch>
                  </div>
                </div>
            </Router>
          </Provider>
        );
      }
    }
MyTwoCents
  • 7,284
  • 3
  • 24
  • 52