passing props from a page to another page in nextjs

Viewed 5224

i have a dummy project.in my project i have two pages.(test1 & test2) i want passing a prop from page1 to page2.i know that i can use useRouter hook but i don't want set this prop as a query string. in my test1 page i have a color variable.this is const and have a yellow value.i want use this color in my page2 as a prop(props.color) this is my test1 page

import React from 'react';
const Test1 = props => {
   const color='yellow';
    return (
        <div>
            test1
        </div>
    );
};

export default Test1;

and this is my test2 page

import React from 'react';

const Test2 = props => {
    return (
        <div>
            Your color is {props.color}
        </div>
    );
};


export default Test2;

3 Answers

Props are passed from a parent component to its child components. What you are asking is to pass props between sibling components (ie. page) which I don't think has a straightforward way to do so. Maybe you can try using React's Context API so that your Test2 is not using any hard-coded value.

Maybe there are too may ways but for me, I think you can use localStorage.

Example:

//in your test1 
//foo is the key, bar is the value
localStorage.setItem("foo", "bar")

//in your test 2 you can get the bar by using foo key
const bar = localStorage.setItem("foo", "bar")

console.log(bar)// bar

And here is a hook called useLocalStorage You can use for that or customize your own.

You can also get data in second page by using getInitialProps after passing the params in Test1 page

Passing Params

import Link from "next/link";

<Link href={{ pathname: '/test2', query: { color: 'yellow' } }}><a>test2</a></Link>

Getting Params

const Test2 = ({color}) => {
    return (
        <div>
            Your color is {color}
        </div>
    );
};

Index.getInitialProps = async ({ query }) => {
  const {color} = query

  return {color}
}

hope this helps.

Related