Search code examples
reactjsreact-routernetlify

Generating multiple links (URL) to display different states of my react App


I have created a Single Page App with react and hosted it on netlify . I am making use of react-router to handle my routing. Is it possible to generate random routes (url) to send as a link for someone to view the current state of my app with a specific data ?

For Example: wwww.forexample.com/myappshowing5dogs --shows my app showing 5 dogs wwww.forexample.com/myappshowing12catssandabook --shows my app showing a different state of my app with 12 cats and a book

How can I generate links (url) to show all the countless possible states of my app?


Solution

  • You can use the useParams functionality of React-Router to do exactly that!

    import {BrowserRouter, Route, useParams} from ReactRouterDOM
    
    const Info = () => {
      let {dogs, cats} = useParams();
      return <div>There are {dogs || 0} dogs and {cats || 0} cats</div>;
      }
    
    const App = () => (
      <BrowserRouter>
        <Route  path="/:dogs?/:cats?/"  component={Info}/>
      </BrowserRouter>)
    
    ReactDOM.render(<App/>, document.getElementById('root'));
    

    And to get Netlify to work nicely with these you need to add /* /index.html 200 into your _redirects file.

    See my demo here: enter image description here

    Sourcecode shows how to do the redirects file and Routing