Doing if logic inside a functional component calling another function

Viewed 31

How can I do if and else logic inside a functional component. For example

const FunctionA = ({ nodes, onOpen}) => {
  nodes.map((item, ind) => (
    if(item.nodes.length===0) {
      return (<div>{item.name}</div>)
    }
    else 
      return (
        <FunctionB   
          name={item.name}
          nodes={item.nodes}        
        />
      );
    }

Not sure if that makes sense. And function B renders the nodes. And calls Function A again to create a nested sidenav which is based on directory structure. I want to check if it's a file and therefore has a property of empty nodes. Or if it's a directory and has further nesting. If has further nesting. Then call function B. Repeat. When I actually try what I put above. I get errors that nothing was returned.

1 Answers

You are not returning anything from FunctionA, and you cant use if/else statements inside an arrow function without a function body.

If you give the arrow function a body, wrap everything in a single topmost element e.g. React.Fragment and return it, it will work.

const FunctionA = ({ nodes, onOpen }) => {
  return (
    <React.Fragment>
      {nodes.map((item, ind) => {
        if (item.nodes.length === 0) {
          return <div>{item.name}</div>;
        } else {
          return <FunctionB name={item.name} nodes={item.nodes} />;
        }
      })}
    </React.Fragment>
  );
};
Related