Skip to content
Advertisement

Routing to a new component from react-bootstrap-table-next?

I have a table of coding problems. When a user clicks on the name of the problem, I want the app to route to a page for a Problem component with props.

Right now I am trying to do so by using formatter and then creating a Route with react-router-dom. However, the component just opens inside of the table, instead of opening the component in its own page.

  function nameFormatter(cell, row) {
    return (
      <>
        <BrowserRouter>
          <Switch>
            <Route
              path={"/problem/" + cell}
              render={() => (
                <Problem
                  id={row.id}
                />
              )}/>
          </Switch>
          <NavLink to={"/problem/" + cell}>{cell}</NavLink>
        </BrowserRouter>
      </>
    );
  }

For a better demo, here’s my sandbox: https://codesandbox.io/s/optimistic-germain-jsc06?file=/src/index.js

I may be overthinking this, and I may be tired, but any help would be appreciated.

Advertisement

Answer

Your routes are structured somewhat incorrectly. Generally speaking, your Home app should really be nothing but a bunch of route definitions. That way you create this “top level” router of sorts. You, on the other hand, make your <BrowserRouter> children subordinate to that table.

This is how your Home element should look:

const Home = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path={"/"}>
          <ProblemTable />
        </Route>

        {problems.map((item) => (
          <Route
            key={item.id}
            path={"/problem/" + item.name}
            render={() => <Problem id={item.id} />}
          />
        ))}
      </Switch>
    </BrowserRouter>
  );
};

So <ProblemTable /> is that table of problems and is rendered at / and the rest of the routes are defined right below it.

Here is a Sandbox for you.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement