skip to Main Content

I have a React component:

const Options = () => {

  // Option logic
  
  if (isOptionOne) {
    return <OptionOne />;
  }

  if (isOptionTwo) {
    return <OptionTwo />;
  }

  if (isOptionThree) {
    return <OptionThree />;
  }

  return null;
};

I render this component inside a parent component:

const ParentComponent = () => {

    <ComponentA />
    <span css={styles.container}
      <Options />
    </span>

  };

What is a clean approach to move the <span> tag to the child component (<Options />), since I want to render this html tag only if <Options /> component does not return null.

2

Answers


  1. You should check if Options component returns null or the component. If the component is returned then render, else don’t.

    You can use Boolean() for checking if it returns null or component.

    if it returns false then don’t render html tag if it does then render.

    The code looks like this:

    const ParentComponent = () => {
      const shouldRenderOptions = Boolean(Options({/*pass the props here */});
    
      return (
        <ComponentA />
        {shouldRenderOptions && (
          <span css={styles.container}>
            <Options />
          </span>
        )}
      );
    };
    
    Login or Signup to reply.
  2. You can simply do it inside each condition:

    const Options = () => {
    
      // Option logic
      
      if (isOptionOne) {
        return (
          <span css={styles.container}>
            <OptionOne />
          </span>
        )
      }
    
      if (isOptionTwo) {
       return (
          <span css={styles.container}>
            <OptionTwo />
          </span>
        )
      }
    
      if (isOptionThree) {
         return (
          <span css={styles.container}>
            <OptionThree />
          </span>
        )
      }
    
      return null;
    };
    

    There is no need to overthink this. This is clean enough.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search