1

I am trying to pass the first: 1 through a link in react js but I am not getting it how to do it. What I have tried is below.

let first = 1;

  <Link
        to={{
          pathname: "/sign",
          state: { variable: 1 },
        }}
      >
        <div className="box">i am pregent</div>
      </Link>
<Routes>
  <Route path="/sign" name="routename" element={Sign}></Route>
</Routes>
export default class Sign extends Component {
  constructor(props) {
    super(props);
    // this.state = { variable: props.location.state.variable };
    const { variable = "defaultValue" } = props.location.state
      ? props.location.state
      : {};
    console.log(variable);
vivek kn
  • 107
  • 1
  • 18
  • 45
  • state just pass to Sign component , you cant get it from App class component – Khanh Le Tran Jan 19 '23 at 09:54
  • @KhanhLeTran are u the one closed this question the answer does not help me i am looking for better answers so i ask u to repoen this question let others help me – vivek kn Jan 19 '23 at 10:00
  • No , moderator do that , not me. Your question is duplicated. You can get the answer below your title or ref this link https://ui.dev/react-router-pass-props-to-link . Try to use useLocation. – Khanh Le Tran Jan 19 '23 at 10:02
  • What part of the duplicate didn't answer your question? It covers passing data via a link and accessing it in a receiving component. Check the `react-router-dom@6` sections. For your code, pass the data on the `Link` component's `state` prop, and to access it in the `Sign` component you'll need to create a custom `withRouter` HOC that uses the `useLocation` hook to access `location.state` and pass it in props to `Sign`. It's all in the post. – Drew Reese Jan 19 '23 at 10:11
  • i have tryed everthing in the link it doesnot woek for me i am passing varaible from a lfuntion compoent to a class componet can u help me with a anwer so i can try @DrewReese – vivek kn Jan 20 '23 at 05:12
  • Please [edit] your post with what you have tried applying from the duplicate post and provide more details about what specifically isn't working. My previous comment is what you should be working on. – Drew Reese Jan 20 '23 at 05:33
  • @DrewReese as u can see in the question i am trying to pass from a funtional compoent to a class compeont and i have tyred location.state in class componet – vivek kn Jan 20 '23 at 05:45
  • I can see that. Like I said, the `Link` component has a `state` prop, i.e. `...`, and to access the passed state in a React Class component you'll need to create a custom `withRouter` Higher Order Component that uses the `useLocation` hook and passed `location` as a prop to the decorated component. The duplicate explains all of this. – Drew Reese Jan 20 '23 at 05:53
  • how to use withRouter & withRouter in a class compoent a answer explaining this will be helpfull so i can try what you are sugesting – vivek kn Jan 20 '23 at 06:10

0 Answers0