How to pass id from one component to another component onclick of an element

Solution 1:

To navigate to another page, you just need history.push(/workspace/${id}).

You don't even need any state here.

import React, { useState } from 'react'
import { useHistory } from 'react-router-dom';
import Workspacelist from '../Workspace/Workspacelist';

function BoardList({ boards }) {
    const history = useHistory()

    const navigate = (id) => {
        history.push(`/workspace/${id}`)
    }
    return (
        <>
            {
                boards.map((board) => (
                    <li key={board.id} className="boardlist" style={styles} onClick={() => navigate(board.id)}>
                        <h3>{board.title}</h3>
                    </li>
                ))}
        </>
    )
}
export default BoardList

To get the id param on the Workspace page, you will need to use the useRouteMatch hook from react-router-dom:

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

function Workspacelist() {
   const {
    params: { id },
  } = useRouteMatch('/workspace/:id');

  console.log(id)
}

Let me know if it solves your problem.

Solution 2:

If you use dom version 6, change the following parts that showed in @HichamELBSI answer.

  • useHistory should change into useNavigate.
  • useRouteMatch should change into useMatch.

After applying those, the codes should be

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

const nav = useNavigate();

const navigate = (id) => {
    nav(`/workspace/${id}`)
}

Then other part should be

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

function Workspacelist() {
   const {
    params: { id },
  } = useMatch('/workspace/:id');

  console.log(id)
}