Home > OS >  Change Parent component based on Child props -> Preact/ React
Change Parent component based on Child props -> Preact/ React

Time:01-27

I'm quite new to programming

In the example below, whenever child component renders null(...or in other words when getPosts() renders null), I want parent component div class to change from className={style.container} to className={style.container.minimized}.

What is the way to re-write this code to make this possible. Appreciate any help.

I have a Parent component like this

const Parent = () => {
    return (
        <div className={style.root}>
            <div>
                <div className={style.container}>
                    <Child />
                </div>
            </div>
        </div>
    );
};






My Child component is like this

const Child = () => {

     <div>
            {getPosts() ? (
                <div>
                    <p>Tomasz from {companyData.companyName}</p>
                    <p>{getPosts()}</p>
                </div>
            ) : null}
        </div>

}

CodePudding user response:

There are several ways to achieve the desired objective.

Presented below is one possible way:

Parent

const Parent = () => {
    const [hasPosts, setHasPosts] = React.useState(false);
    return (
        <div className={style.root}>
            <div>
                <div className={hasPosts ? style.container : style.container.minimized}>
                    <Child hasPosts={hasPosts} setHasPosts={setHasPosts} />
                </div>
            </div>
        </div>
    );
};

Child

const Child = ({hasPosts, setHasPosts, ...props}) => {
  // if getPosts() is an API, may choose to make the call
  // within useEffect hook. For simplicity, it is placed as-is below.
  const posts = getPosts();
  if (posts) setHasPosts(true);
  else setHasPosts(false);
  return (<div>
    {hasPosts ? (
      <div>
        <p>Tomasz from {companyData.companyName}</p>
        <p>{posts}</p>
      </div>
    ) : null}
  </div>);
};

Explanation

  • Declare hasPosts and setHasPosts in parent (with useState hook)
  • Pass both as props down to the child
  • Make call to getPosts() in child and store result in local posts
  • Invoke setHasPosts to set hasPosts to true if there are posts; otherwise to set it as false.
  • Use posts within the child's JSX
  • Use hasPosts in the parent's JSX and conditionally apply the appropriate style in the parent

PS: There are plenty of amazing resources on the internet that explain these details in a much more elegant and informative way.

  •  Tags:  
  • Related