Home > database >  How can I navigate to another page in react?
How can I navigate to another page in react?

Time:01-31

I use react-router-dom, but when i click on the button, the page is rendered on top of the main one.

I do not need a full-fledged menu with a page transition. I have a button in the component and when I click it, I need to go to the next pageenter image description here

enter image description here

import React from "react"
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom'
import Profile from "../../profile/profile"

import "./UserBlock.scss"

const UserBlock = ({name,city,company}) => {
return (
    <Router>
    <div className="userBlock">
    <div className="userBlock__info">   
    <div><strong>ФИО: </strong>{name}</div>
      <div><strong>Город:</strong> {city}</div>
      <div><strong>Компания:</strong> {company}</div>
        <button><Link to="/profile">Подробнее</Link></button>
        </div>
    </div>
    <Routes>
    <Route path="/App" element={<App/>}/>
    <Route path="/profile" element={<Profile/>}/>
    </Routes>
    </Router>
 )
    
}


export default UserBlock

App.JS

   return(
    <div className='usersList'>
    <div className='usersList__sidebar'>
    <span>Сортировка</span>
    <SortButton button={sortCity} text="по городу" />
    <SortButton button={sortCompany} text="по компании"/>
    </div>
    <div className="usersList__lists">
      <h3>Список пользователей</h3>
      {isLoaded ? <img src={preloader} alt="preloader"/> : (
        <div className="usersList__items">
        {users.map(user => (
          <div className="usersList__userCard">
            <UserBlock
              key={user.id}
              name={user.name}
              city={user.address.city}
              company={user.company.name}/>
          </div>
        ))}
        <span>Найдено {count} пользователей</span>
      </div>)}
     </div>
    </div>
  )

CodePudding user response:

The <Router> needs to go around everything that you want to change when you navigate.

The picture suggests that you have something like:

<main>
    { users.map(user => <UserBlock {...user} /> }
</main>

in a parent component.

You need to do your routing there and not inside each one of the UserBlocks.

  •  Tags:  
  • Related