Home > Software engineering >  NEXTJS ReactJS passing props from page to all its sub-components
NEXTJS ReactJS passing props from page to all its sub-components

Time:08-08

It's possible to pass all the props of the page to all its children components implicitly (without passing as parameter)?

I need something like this:

export default function Home({ user }) {
  
  if (!user) {
    return (
      <>
        <component1/>
        <component2/>
        <component3/>

      </>
    );
  } else {
    return (
      <></>
    );
  }
}

export async function getServerSideProps(context) {
  const { Auth } = withSSRContext(context);
  try {
    const user = await Auth.currentAuthenticatedUser();
    return {
      props: {
        user: JSON.parse(JSON.stringify(user)),
      }
    }
}

I need that user is available to component1, component2, component3 and all its sub-components without passing explicitly. I've read that you can use context for this. But I'm using amplify aws and I don't know if it's possible ...

CodePudding user response:

First your components should be capitalize. You can use context to pass the values without the use of the props. For that you need to setup context using createContext

import { createContext } from "react";

const UserContext = createContext()
export default function Home({ user }) {

if (user) {
 return (
  <UserContext.Provider value={user}>
    <Component1/>
    <Component2/>
    <Component3/>
    </UserContext.Provider>
 );
} else {
 return (
  <></>
 );
}}

And then inside the Component1 or 2 or 3 ... You can use useContext to get the value.

import { useContext } from "react"

function Component1() {
const user = useContext(UserContext);

return (
 <>
  <h1>Component 1</h1>
  <h2>{`Hello ${user} again!`}</h2>
 </>
);
}

CodePudding user response:

You can use react context, redux, recoil. Recoil is easy to use.

CodePudding user response:

Context provides a way to pass data through the component tree without having to pass props down manually at every level, It's react concept, AWS Amplify will not restrict from using this. Feel free to use it here.

  • Related