0

Using react-router-dom in server-side react creates an error.

Invariant Violation: Browser history needs a DOM

I am using react-router-dom BrowserRouter to render my component in div if url match my component path.

  const routes = [

  { path: 'dashboard',
    exact: true,
    component: Dashboard
  },
  { path: 'notification',
    exact: true,
    component: Notification
  }

];

and then use this code to target specific div to render my component:

<div>
     { routes.map((route, index) => (
       <Route
            key={index}
            path={`${match.url}/${route.path}`}
            exact={route.exact}
              />
        ))}
</div>

But this code work only in client-side react. How can I implement this to server-side?

2 Answers 2

0

Please take a look at official documentation, you need to use different history provider for server side rendering because you don't have a real DOM (and browser's history) on server.

You may also want to use memory history because it works fine on server side.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi sir. I tried your solution but MemoryRouter only support one child element.
@JazulKerk you can easily wrap your routes into <div>. Actually router component can wrap your application's root element and it will be the only child element for it.
sorry I cant comprehend your explanation :( . can you give me an actual code example for this? thank you.
@JazulKerk of course, please take a look at this gist, hope it will help.
0

Looks like you missed adding component to the Route.

<div>
         { routes.map((route, index) => (
           <Route
                key={index}
                path={`${match.url}/${route.path}`}
                exact={route.exact}
                component={route.component}
                  />
            ))}
    </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.