1

in React router dom can i pass a props in a Link?

Is there a way that i can pass props into Link then just the component?

I'm trying to pass props inside a Link like this.

function App(){
    const test = "Hello"
    return(
        <Link to="/detail" test={test}> detail </Link>
    )
}

In my detail component i can call like this.

function detail(){
return(
    <p>{test}</p>
    )   
}

I'm sorry if this example is very hard to understand, I don't know how to give proper example.

Josh Lee
  • 81
  • 5

1 Answers1

2

Using state prop you can as below

Using React Router - V5

Docs ref for Link - V5

function App(){
    const test = "Hello"
    return(
        <Link to= {{ pathname : "/detail",  state: { test: "dummy"} }}> detail </Link>
    )
}

Using React Router - V6

Docs ref for Link - V6

function App(){
    const test = "Hello"
    return(
        <Link to= "/detail"  state= {{ test: "dummy" }} > detail </Link>
    )
}

and get the value using useLocation hook which is same in V5 & V6

In my detail component I can call like this.

function detail(){
const {state} = useLocation();
return(
    <p>{state.test}</p>
    )   
}
KcH
  • 3,302
  • 3
  • 21
  • 46
  • 1
    Since it's not clear at all which version of `react-router-dom` OP is using, just be aware that the [`Link`](https://reactrouter.com/en/main/components/link) component API changed in v6, `state` is a prop on the link instead of a property on the `to` object. – Drew Reese Sep 27 '22 at 15:10
  • Sure @Drew, updated the answer with both versions , thanks for the hint – KcH Sep 27 '22 at 16:45