0

Here i want to load the ShowIt component as a nested route but it doesn't work i mean when i click on the link i go to route of that but the ShowIt component (hello world) doesn't load and i really need to solve this problem
please help me

    import React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from 'react-router-dom';

const ShowIt = <div>Hello world</div>;

const Links = (
  <div>
    <Link to="news/components">Go to Components</Link>
    <br/>
    <Link to="news/states-vs-props">Go to states vs props</Link>
  </div>
);

const News = () => {
  return (
    <div>
      {
        Links
      }
      <Router>
        <Switch>
          <Route path="news/:id">
            <ShowIt />
          </Route>
        </Switch>
      </Router>
    </div>
  );
};

export default News;

1 Answer 1

1

You should not use <Link> outside a <Router>. So do this:

<Router>
  {Links}
  <Switch>
    <Route path="/news/:id">
      <ShowIt />
    </Route>
  </Switch>
</Router>

There are few more issues in your code:

  1. Make ShowIt a react component:
const ShowIt = () => <div>Hello world</div>;
  1. Use a /some-route instead of some-route:
<Link to="/news/components">Go to Components</Link>

And, to access id in ShowIt component:

import { useParams } from "react-router-dom";
// ...
const { id } = useParams<{ id: string }>();
Sign up to request clarification or add additional context in comments.

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.