Home > other >  URL parameter with React-Router
URL parameter with React-Router

Time:12-31

//ArticlePage

const ArticlePage = ({ match }) => {
    const name = match.params.name;
    return (
    <>
        <h1>
            This is {name} Article
        </h1>
    </>
);
    }
export default ArticlePage;

//App

import { BrowserRouter, Route, Routes } from 'react-router-dom';
import NavBar from "./NavBar";
import NotFound from "./pages/NotFound";
import ArticlePage from "./pages/ArticlePage";

function App () {
  return (
    <div className="App">
      <BrowserRouter>
        <NavBar />
        <Routes> 
          <Route exact path='/' element ={<HomePage />} />
          <Route path = '/topic' element = {<Topic />} />
          <Route path = '/about' element = {<AboutPage />} />
          <Route path = '/article/:name' element = {<ArticlePage />} /> 
          <Route path = '*' element = {<NotFound />} />
        </Routes>
      </BrowserRouter>
    </div>
   );
}

export default App;

//NavBar Page

import { Link } from 'react-router-dom';
import './NavBar.css';

const NavBar = () => (
    <nav>
        <ul>
            <li className='li'>
                <Link to ="/" className='link' > Home </Link>
            </li>
            <li className='li'>
                <Link to ="/about" className='link' > About </Link>
            </li>
            <li className='li'>
                <Link to = "/article" className='link'> Article </Link>
            </li>
            <li className='li'>
                <Link to = "/topic" className='link' > Topic </Link> 
            </li>
        </ul>
    </nav>
);

export default NavBar;

enter image description here

**I am trying to pass URL parameter using variable 'name' but soon as i access ArticlePage I get 404:Not Found (content of my NotFound Page) .I'm trying to get value of 'name' variable using props (match) in ArticlePage but I'm unable to render it. Fairly new to React, any hint or solution would be appreciated. I'm using React v6. **

CodePudding user response:

Try this code it's works

import { useParams } from 'react-router-dom';

const ArticlePage = () => {
   const params = useParams();
  return (
    <>
      <h1>
        This is {params.name} Article
      </h1>
    </>
  );
}
export default ArticlePage;
  • Related