Home > Enterprise >  How to fetch the userid of clicking on the name in react?
How to fetch the userid of clicking on the name in react?

Time:08-12

In my project I want to access the name of student after clicking the present button .

So it means if I click on "arijit" name then it should log on console "arijit"

    const StudentList = () => {
      const [studentlist, setStudentList] = useState([]);
      const studentdataList = async () => {
        const result = await fetch("http://localhost:5000/api/students");
        const studentResult = await result.json();
        setStudentList(studentResult);
        console.log(studentResult[0].name);
        
      };
    
      function present(){
        // what to write here?
      }
    
      useEffect(() => {
        studentdataList();
      },[]);
    
      return (
        <div>
          {studentlist.map((student) => {
            return (
              <Card style={{ width: "18rem" }}>
                <Card.Body>
                  <Card.Title> {student.name} </Card.Title>
                  
                  <Button onClick={present}>present</Button>
                  <Button>abscent</Button>
                </Card.Body>
              </Card>
            );
          })}
        </div>
      );
    };
    
    export default StudentList;

CodePudding user response:

The simplest solution would be to pass the student's name into the present function inside of the onClick handler.

    const StudentList = () => {
      const [studentlist, setStudentList] = useState([]);
      const studentdataList = async () => {
        const result = await fetch("http://localhost:5000/api/students");
        const studentResult = await result.json();
        setStudentList(studentResult);
        console.log(studentResult[0].name);
        
      };
    
      function present(name){
        console.log(name);
      }
    
      useEffect(() => {
        studentdataList();
      },[]);
    
      return (
        <div>
          {studentlist.map((student) => {
            return (
              <Card style={{ width: "18rem" }}>
                <Card.Body>
                  <Card.Title> {student.name} </Card.Title>
                  
                  <Button onClick={() => present(student.name)}>present</Button>
                  <Button>abscent</Button>
                </Card.Body>
              </Card>
            );
          })}
        </div>
      );
    };
    
    export default StudentList;

  • Related