0

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.

1 Answer 1

1

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);
            }
        }
    }

Sign up to request clarification or add additional context in comments.

4 Comments

thanks, i changed it, but it still functions the same. i get, for example, page/3 as before, but still nothing when i type it into url
The problem is not the link you need to set id as a state so when the current page change current id in body also change. Let me edit my answer
I just update my answer you can add to your code to see does it work
OMG thank you so so much! Thank you for looking at the code and actually fixing this, i've been at it for the whole week. And i've never though of trying componentDidUpdate. Ty ty ty!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.