简体   繁体   中英

How would I attach a randomly generated string to react router useParams()?

My question explanation:

Basically I am trying to create a multiplayer web game. I am running into a logical issue when trying to understand how to get a new page to open upon "Start new Game".

I would like to randomly generate a string through a function then use that result as the:id in my url. I can successfully create the randomly generated string, but still confused on how to use it in my useParams() for react-router v5.


If possible I would also like to connect a socket to each generated url that way it splits concerns easily and everything stays in place.


So it would be in logic of pages

  1. Landing Page with Start new Game button
  2. Click New game button and new tab opens with Game content that pertains to that specific game.

If you have any other insight to a different way to handle this, it would be greatly appreciated!


my code

App.jsx

import React from 'react';
import Landing from './Landing/Landing.jsx';
import Game from './Game/Game.jsx';
import { HashRouter as Router, Switch, Route } from 'react-router-dom';
import './Styles/styles.scss';

const App = () => {
    return (
        <Router>
            <Switch>
                <Route exact path="/" component={Landing} />
                <Route exact path="/game/:id" component={Game} />
            </Switch>
        </Router>
    )
}

export default App

Landing.jsx

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


const Landing = () => {
    const { id } = useParams();
    const [randomRoom, setRandomRoom] = useState('');

        /*
            This functions needs to create :id for react-router and also create room id for socket.io
        */

    const getRandomString = (length) => {
            let randomChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';
            for ( let i = 0; i < length; i++ ) {
                result += randomChars.charAt(Math.floor(Math.random() * randomChars.length));
            }
        setRandomRoom(result)
        }

    return (
        <div>
            <button onClick={() => { 
                getRandomString(20);
                }}>
                Start New Game
            </button>
        </div>
    )
}

export default Landing

Game.jsx

import React from 'react'

const Game = () => {
/*
  This will hold the content for game page including Map, scoreboard, usernames, list of items, etc
*/
    return (
        <div>
            HELLO FROM GAME
        </div>
    )
}

export default Game

Visuals of what I want

Since the url /game/:id renders the Game component, that's where you need to use useParams to get the value of that URL parameter.

So your Game code will look like this:

const Game = () => {
    const { id } = useParams();

    return (
        <div>
            HELLO FROM GAME
        </div>
    )
}

And then you can use that ID for whatever purpose you had in mind.

You can solve this using react-router-dom 's Link component, with the to property set to the desired URL (including the :id section).

Then, you can make the network requests from the new page, extracting the id: section of the URL using useParams :

/// first-page.jsx
export const FirstPage = () => {

  const getRandomString = useCallback(() => {
    // generate your string...
    return 'your_random_string';
  }, []);

  return (
    <>
      <div>Some other components ...</div>
      <Link
        to={`/second/page/:${getRandomString()}`}
      >
        Start Game!
      </Link>
    </>
  );
};
/// second-page.jsx
export const Secondpage = () => {
  const { id } = useParams();

  return (
    <div>The page's ID is: {id}</div>
  );
};
/// index.jsx
ReactDOM.render(
  <Router>
    <Switch>
      <Route exact path="/first/page">
        <FirstPage />
      </Route>
      <Route path="/second/page/:id">
        <SecondPage />
      </Route>
    </Switch>
  </Router>
);

If you look at the route in the last snippet, you'll see that the last fragment of the URL is identified by react-router as :id . This matches the pattern used in the first-page and can then be read by useParams in second-page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM