简体   繁体   中英

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

I'm trying to pass this is as id as props to another component which is not a child of the component. I was considering using context but i wanted to know if there was another way to it, since I'm quite new to react I'm looking for a more efficient way.

This is the component where the id of the element clicked is being generated. When i logged it the data is correct an no problems was notified. I first tried passing it as props as seen below but since i didn't want it to be seen on that page i didn't pass it to the main return statement neither did i call the method in it, but then it returned undefined in the component where i wanted to make use of it

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

function BoardList({ boards }) {
    const [currentid, setcurrentid] = useState('')
    const history = useHistory()

    const navigate = (id) => {
        setcurrentid(id);
        console.log(id)
        history.push(`/workspace/${id}`)
        return(
            <Workspacelist id = {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

PS: Firebase is being incoporated in this project, i was thinking that might be the reason cause it's my first time using firebase so maybe I'm missing something since all the data is coming from the server

And this is the component i want to pass it to

import React, { useState, useEffect } from 'react'
import Firebase, { db } from '../Firebase/Firebase';
import { Todo } from './List';


function Workspacelist({ id }) {
    const [updatedId] = useState(id)

    const [show, setshow] = useState(false);


    const [Todos, setTodos] = useState([]);//Todolist
    const [ToDo, setToDo] = useState('');

     useEffect(() => {
         const docRef = db.collection("boards").doc(updatedId).get().then(doc => {
             if (doc.exists) {
                 setTodos(doc.data().todo);
                 console.log("Document data:", doc.data().todo);
             } else {
                 console.log("No such document!");
             }
         }).catch(function (error) {
             console.log("Error getting document:", error);
         });
         return docRef
     })


    return (
        <div className="workspacelist">
            <div className="todo">
                <div>
                    <b>To Do</b>
                    <b>...</b>
                    <Todo Todos={Todos} />
                    <span onClick={() => { setshow(current => !current) }} style={{ display: show ? 'none' : 'block' }}>+ Add a card</span>
                </div>
                <div className="add" style={{ display: show ? 'block' : 'none' }}>
                    <textarea placeholder="Enter a title for this card..." value={ToDo} onChange={(e) => { setToDo(e.target.value) }} />
                    <button className="addcard" onClick={one}>Add Card</button>
                    <button onClick={() => { setshow(current => !current) }}>X</button>
                    <button className="more">...</button>
                </div>
            </div>
        </div>
    )
}

export default Workspacelist

Thanks in advance i did appreciate the help even if i have to rewrite it just tell me the way you would do it if you were in my shoes

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.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM