I have a parent component that renders 4 children. If all 4 child components return null, I want to render a different component.
What I would like to do:
const Child = () => {
return(<div> hi </div>); // I expect if I return(null) to render Nothing Found whic doesn't happen
}
const Parent = () => {
const children = [1, 2, 3].map(() => {
return (<Child />);
});
return (
<div>
{children.some(element => element !== null) ? (
children
) : (
<div>Nothing found</div>
)}
</div>
)
}
Assuming the decision of whether to render null or not is being made here in the Parent component, you can do something like the following:
function Parent() {
const children = [1, 2, 3].map(() => {
return null, or whatever;
});
return (
<>
{children.some(element => element !== null) ? (
children
) : (
<div>Nothing found</div>
)}
</>
);
}
EDIT: If the parent component is always returning elements, and it's up to the child component to decide whether to return null or not, then your options are very limited. The child won't render until the future (it's right after the parent finishes rendering, but that's still in the future), so the elements that the parent has created don't have any information about what will eventually be rendered.
The best i can think of is to have some static utility function which gets called as part of the child's logic, and which you can call in the parent to get a preview of what the child might do. For example:
export const willRender = (props) => {
if (/* check something on the props */) {
return false;
} else {
return true;
}
}
export const Child = (props) => {
if (willRender(props)) {
return <div>Hello World</div>
} else {
return null;
}
}
Used in the parent something like this:
function Parent() {
return (
<>
{[1, 2, 3].some(() => willRender({ /* whatever props */ })) ? (
[1, 2, 3].map(() => <Child /* same props */ />)
) : (
<div>Nothing found</div>
)}
</>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With