Home > Back-end >  Why is it not reading the params?
Why is it not reading the params?

Time:11-24

I am trying to read the code but its returning undefined. I want to read the code from the route and display it in h3 tag.

The Routing

 <Router>
  <Routes>
    <Route path="/" element={<p>Homepage</p>} />
    <Route path="/join" element={JoinRoomPage()} />
    <Route path="/create" element={CreateRoomPage()} />
    This is the roomCode i want to read in the Room Component
    <Route path="/room/:roomCode" element={Room()} />
  </Routes>
</Router>

The Room Component

import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";

export default function Room(props) {
  const [room, setRoom] = useState({
    votesToSkip: 2,
    guestCanPause: true,
    isHost: false,
  });

  let { roomCode } = useParams();

  return (
    <div>
      <h3>{roomCode}</h3>
      <p>Votes: {room.votesToSkip}</p>
      <p>Guest Can Pause: {room.guestCanPause}</p>
      <p>Host: {room.isHost}</p>
    </div>
  );
}

Thanks in advance

CodePudding user response:

The route components should be passed as JSX, not as an invoked function.

<Router>
  <Routes>
    <Route path="/" element={<p>Homepage</p>} />
    <Route path="/join" element={<JoinRoomPage />} />
    <Route path="/create" element={<CreateRoomPage />} />
    <Route path="/room/:roomCode" element={<Room />} />
  </Routes>
</Router>

CodePudding user response:

Router

<Router>
  <Routes>
    <Route path="/" element={<p>Homepage</p>} />
    <Route path="/join" element={JoinRoomPage()} />
    <Route path="/create" element={CreateRoomPage()} />
    This is the roomCode i want to read in the Room Component
    <Route path="/room/:roomCode" element={<Room />} />
  </Routes>
</Router>

Room Component

import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";

const Room = (props) => {
    let { roomCode } = useParams();
    const [room, setRoom] = useState({
        votesToSkip: 2,
        guestCanPause: true,
        isHost: false,
    });

    return (

        <div>
            <h3>{roomCode}</h3>
            <p>Votes: {room.votesToSkip}</p>
            <p>Guest Can Pause: {room.guestCanPause}</p>
            <p>Host: {room.isHost}</p>
        </div>
    );
}

export default Room;

  • Related