useParams in React Router tut 17

              useParams in React Router




1 st create Link user : 

<NavLink  activeClassName="active_class" to="/user"> User </NavLink>

2nd metion link in route :

<Switch>
    {/* To Pass The Props to bellow about component */}
      <Route exact path="/" component={()=><About text="About US" />}/>
      {/* We can also use render in place of component like bellow */}
      <Route exact path="/contact" render={Contact}/> 
      <Route path="/contact/service" component={Service}/>
      <Route path="/user/:fname/:lname" component={User}/> // here we metion
      <Route component={ErrorMsg}/>
    </Switch>


Explanation : If we have to pass any parameter through link or we have to show any thing to link 
dynamically , then we have to metion it like " /:paramName" .

3rd Get parameter in user component :

import React from 'react';
import {useParamsfrom 'react-router-dom';
// let User = ({match}) =>{
//     return(              // old way 
//         <>
//    <h1>I am {match.params.fname} User</h1>

//         </>
//     )
// }

let User = () =>{
    var {fnamelname} = useParams(); // new way using hook
    return(
        <>
   <h1>I am {fname} {lname} User</h1>

        </>
    )
}

export default User;
 
Explanation : 
var {fnamelname} = useParams()

useparams can return many parameter so i.e we have get it under { } as object.

imp Note : We have use same variable in User  component which we used in route path. like

<Route path="/user/:fname/:lname" component={User}/>





















Comments