Home > Back-end >  Setting up a working URL with React Router
Setting up a working URL with React Router

Time:09-17

I'm having some real trouble setting up a react router and would really appreciate some suggestions. I have an app with multiple pages, and i want the app to display the page i'm on in url and be able to go to specific page through url. But i just cant seem to get it working.

The route path is: <Route path="/page/{:id}" component={Body} />

It's calling Body, which is my main Class component where most of the code and logic is. But most of the threads and tutorials i've seen use either useEffect or useParams, which can't be done in a class component.

The app is simple, all it does is change between pages and calls api on every page to get different text and button numbers.

So what i'm doing now is i have a Link tag wrapped around my buttons with page numbers <Link key={index} to={`/page/${links.label}`}>. Those buttons are in a seperate function component. And i see the change in url based on which page i'm on. But i want to set it up so i can type the url directly.

buttons:

const renderPageNumbers = apiPagingSliced.map((links, index ) => {
        return <Link key={index} to={`/page/${links.label}`}>
                    <button key={index} id={links.label}
                    onClick={props.handleClick}
                    >{links.label}
                    </button>
                </Link>
        })

and it just seems very incomplete. I tried using useParams, but couldn't get it to work.

CodePudding user response:

Add this into your Body Component so when id param change your page get update and update your localStorage too

componentDidUpdate(prevProps, prevState, snapshot){
        if(prevProps){
            if(prevProps.match.params.id !== this.props.match.params.id){
                const id = this.props.match.params.id;
                localStorage.setItem("currentPage", id)
                this.setState ({
                    currentPage: id});
                this.fetchApi(id);
            }
        }
    }

  • Related