Search code examples
javascriptreactjsonclickviteonchange

How can I redirect user from 1st component to second component using onclick function


import React from 'react'
import { useNavigate } from 'react-router-dom'
import user from './api/Userdata'
import InsideChat from './InsideChat'
const Chats = () => {
  const seeMsg = (id) => {
//here: what can I write that it will redirect user to IndideChat component
    console.log(id)
  }
  return (
    <div className="main">
        { user.map((currUser) =>{
        return(
        <div className="user w-full h-14 my-1 flex justify-between content-center" key={currUser.id} onClick={() => seeMsg(currUser.id)}>
            <img className='shadow rounded-full max-w-full h-11 w-11 align-middle border-none' src={currUser.image} alt=""/>
            <div className="name pr-16 pl-1 justify-center text-center flex items-center text-gray-900 font-medium mb-1">{currUser.name}</div>
            <div className="time font-thin text-xs text-center flex items-center pr-2">{currUser.time}</div>
        </div>
          )})}
      </div>
  )
}
export default Chats

How can I redirect user to first component to second component using onclick. There is a comment inside seeMsg function. Second Component is also declared as InsideChat. How can I redirect user to that.


Solution

  • You can navigate only to the routes of different components:

    const Chats = () => {
      const navigate = useNavigate();
      const seeMsg = (id) => {
       navigate('/yourcomponentpath') 
       //or if you want dynamic navigation:
       navigate(`/yourcomponentpath/{id}`) 
      }
      return(...)
    }