We can pass data between pages in ReactJS in both class as well as functional components using Links v5 react-route and useNavigate, useLocation (hooks) v6 of react-router.

Let’s see how we can achieve the above in the class component

In PostScreen (Component) we have a Create Post link, by clicking the link we will go to the "/post-details" page with the data we passed in the state object.

import React from 'react';
import { Link } from 'react-router-dom';
export default class PostComponent extends React.Component {
    render() {
        return (
            <>
                <Link to={{
                    pathname: '/post-details',
                    state: {
                        post_id: 1,
                        post_name: 'Lorem Ipsum',
                        post_description: "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
                    }
                }} >
                    Create Post
                </Link>
            </>
        )
    }
}

Now in the PostDetailsScreen (Component), we can access the passed state object as below:

import React from 'react';
export default class PostDetailsScreen extends React.Component {
    //Log props data
    consoleLog() {
        console.log(this.props.location.state);
    }
    render() {
        return (
            <>
                <button onClick={() => { this.consoleLog() }}>Log Props Data</button>
            </>
        )
    }
}

Now we have to achieve the above in the functional component

We will need useNavigate, useLocation hooks to achieve routing in functional component

import React from 'react';
import { useNavigate } from 'react-router-dom';
export default function PostScreen() {
    const navigate = useNavigate();
    const createPost = () => {
        navigate('/post-details',
            {
                state: {
                    post_id: 1,
                    post_name: 'Lorem Ipsum',
                    post_description: "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
                }
            });
    }
    return (
        <>
            <div>
                <span onClick={() => { createPost() }}>
                    Create Post
                </span>
            </div>
        </>
    );
}

Now we will be able to access the post data on the post details screen.

import React from 'react';
import { useLocation } from 'react-router-dom';
export default function PostDetailsScreen() {
    const { state } = useLocation();
    return (
        <>
            <div>{state.post_id}</div>
            <div>{state.post_name}</div>
            <div>{state.post_description}</div>
        </>
    )
}

Thank you for reading this article, I really appreciate it. If you have any questions feel free to leave a comment.

Leave a Reply