user13116294
user13116294

Reputation:

How do I add BrowserRouter in index.js file of a react app?

I tried using the following code to add Routes to my app. I added BrowserRouter to index.js file of my react app as follows,

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';


const app = (
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

ReactDOM.render(app, document.getElementById('root'));
serviceWorker.unregister();

But I am getting the following error

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
Check the render method of `Context.Consumer`.

Can anyone let me know why is it so ?

Upvotes: 1

Views: 5420

Answers (2)

Champion
Champion

Reputation: 774

Try this one. It works for me

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

App component

export default App

Upvotes: 0

nip
nip

Reputation: 1697

The issue is that your are passing an object to the render method, which expects

a string (for built-in components) or a class/function (for composite components)

like the error message says.

Before:

const app = (
    <BrowserRouter>
       <App />
    </BrowserRouter>
);

After:

const app = () => (
    <BrowserRouter>
       <App />
    </BrowserRouter>
);

Upvotes: 1

Related Questions