Alexander
Alexander

Reputation: 35

How do I reset component's states to default when new props are passed in?

I am currently creating a Next.js project and currently have a custom Layout implemented. I would like to reset my header component when a new page is clicked so that the menu will go back to its default version. Does anyone know how to do this?

import { Fragment } from "react";
import Header from "./header";
import Footer from "./footer";
import classes from "./layout.module.css";

function Layout(props) {
  return (
    <Fragment>
      <Header />
      <main className={classes.body}>{props.children}</main>
      <Footer className={classes.bottom} />
    </Fragment>
  );
}

export default Layout;

Upvotes: 1

Views: 56

Answers (1)

Maradox
Maradox

Reputation: 640

Yes, you can easily do it using key, which is super cool.

function Layout(props) {
  return (
    <Fragment>
      <Header key={props.selectedRoutePathName} />
      <main className={classes.body}>{props.children}</main>
      <Footer className={classes.bottom} />
    </Fragment>
  );
}

You can select a unique value (in your case, route pathname) and pass it as a key to the Header component. And when the route path name changes, React will think of it as a different component and create another one. So the Header component will get the default state as you expected.

You can check my code-sandbox here for reference. https://codesandbox.io/s/react-hooks-counter-demo-forked-t1llj?file=/src/index.js

Upvotes: 2

Related Questions