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
hasPostsandsetHasPostsin parent (with useState hook) - Pass both as props down to the child
- Make call to
getPosts()in child and store result in localposts - Invoke
setHasPoststo sethasPoststo true if there are posts; otherwise to set it as false. - Use
postswithin the child's JSX - Use
hasPostsin 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.
