'React making url dynamic

So I want to make a URL a bit more dynamic, I set up this example for clarity. I have three buttons, home, about and game. I've set them up using params i.ex '/:home'. What I want to do is make it so that the routes are connected to a variable so that React dont confuse home, about and game with each other. Here is my first component with buttons to change the url.

import React from 'react'
import { useNavigate } from 'react-router-dom'

const Buttons = () => {

  const navigate = useNavigate()
  let home = '/home'
  let about = '/about'
  let game = '/game'

  return (

    <div>Buttons
        <button onClick={()=>navigate(home)}>Home </button>
        <button onClick={()=>navigate(about)}>About </button>
        <button onClick={()=>navigate(game)}>Game </button>
    </div>
  )
}

export default Buttons

Here is my routing

import React from 'react'
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'
import Buttons from '../components/buttons/Buttons'
import About from '../pages/About/About'
import Game from '../pages/Game/Game'
import Home from '../pages/Home/Home'

const Routing = () => {
  return (
    <Router>
      <Buttons/>
        <Routes>
            <Route path='/:home' element={<Home />}/>
            <Route path='/:about'element={<About/>}/>
            <Route path='/:game' element={<Game/>}/>
        </Routes>
    </Router>
  )
}

export default Routing

Should I perhaps useContext and assign variables?

App.js and index.js

import React from 'react'
import './app.css'
import Routing from './routes/Routing'


const App = () => {
  return (
      <div>
          <Routing/>
      </div>
  )
}

export default App
import React from 'react'
import ReactDOM from 'react-dom';
import './index.css'
import App from './App'

ReactDOM.render(
<App/>,
document.getElementById('root'))

Thanks in advance!



Solution 1:[1]

You could just create a file like constants.js and create your navigation object that contains something like:

export const url = {
  HOME: '/home',
  ABOUT: '/about',
}

This can then be imported throughout your project and accessed like so:

()=>navigate(url.HOME)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TomS