Render React child component with conditional rendering and one general wrapping html element

76 views Asked by At

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.

3

There are 3 answers

6
root_coding On

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>
    )}
  );
};
0
Nymeria On

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.

0
Ali NAghavi On
const ChoiceComponent = () => {
  let selectedComponent = null;

  if (conditionForOptionA) {
    selectedComponent = <OptionA />;
  } else if (conditionForOptionB) {
    selectedComponent = <OptionB />;
  } else if (conditionForOptionC) {
    selectedComponent = <OptionC />;
  }

  return selectedComponent ? (
    <span css={choiceStyles.wrapper}>{selectedComponent}</span>
  ) : null;
};