Pass a parameter/attribute from one React screen to another

Tiempo de lectura: 2 minutos

Hello, today we are going to learn how we can pass a parameter from one React screen to another.

Step 1: Installing React Router v6

If you haven’t already, install React Router v6:

npm install react-router-dom@next

Step 2: Configuring React Router

In your App.js file, set up routes using BrowserRouter and Route:

// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Screen1 from './Screen1';
import Screen2 from './Screen2';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Screen1 />} />
        <Route path="/dashboard/:userId" element={<Screen2 />} />
      </Routes>
    </Router>
  );
}

export default App;

Step 3: Navigating with ID

In your Screen 1 component (Screen1.js), use useNavigate to handle navigation:

// Screen1.js
import React from 'react';
import { useNavigate } from 'react-router-dom';

const Screen1 = () => {
  const navigate = useNavigate();

  const handleClick = (id) => {
    navigate(`/dashboard/${id}`);
  };

  return (
    <div>
      {/* Screen 1 content */}
      <button onClick={() => handleClick(123)}>Go to Dashboard with ID 123</button>
    </div>
  );
};

export default Screen1;

Step 4: Retrieving ID in Screen 2

In your Screen 2 component (Screen2.js), use useParams to retrieve the ID:

// Screen2.js
import React from 'react';
import { useParams } from 'react-router-dom';

const Screen2 = () => {
  const { userId} = useParams();

  return (
    <div>
      {/* Screen 2 content */}
      <p>User ID: {userId}</p>
    </div>
  );
};

export default Screen2;

Step 5: Running the Project

Make sure your application is running:

npm start

Open your browser and visit http://localhost:3000. Clicking the button on Screen 1 should correctly redirect you to Screen 2 with the user ID displayed.

Leave a Comment