Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Different Component if All Components return Null in ReactJS

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>
  )
}
like image 574
Danny Avatar asked Aug 31 '26 22:08

Danny


1 Answers

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>
       )}
    </>
  );
}
like image 106
Nicholas Tower Avatar answered Sep 03 '26 21:09

Nicholas Tower