elijah
elijah

Reputation: 177

Best way to handle conditional parent containers in React?

Let's say I have two different styles for a component, one that is flat, and one that is floating/rounded. The floating/rounded one requires an extra div wrapping (li provides a little padding, div gets extra 'float styles'). The styles aren't that important, but here is the solution I've come to that requires the least amount of code:

const Parent = ({variant}) => {
const child = [<p>The children go here!</p>]

if (variant === "rounded") {
 return (
      <Rounded>
          {child}
      </Rounded>
  )
} else {
 return (
      <Flat>
          {child}
      </Flat>
  )
}

const Rounded = ({ children }) => {
  const classes = useStyles();
  return (
    <li className={`${classes.li} ${classes.li_rounded}`}>
      <div className={classes.div}>{children}</div>
    </li>
  );
};

const Flat = ({ children }) => {
  const classes = useStyles();
  return (
    <li
      className={`${classes.li} ${classes.li_flat}`}
    >
      {children}
    </li>
  );
};

Is this the best way to do this with the most minimal amount of code? I can't seem to find a better solution. The code can still end up being quite long if the "wrapper" components/elements themselves require multiple props (then I'm writing a bunch of repetitive code relating to the props, and repetition is the reason why I'm doing this).

Upvotes: 3

Views: 3389

Answers (1)

Alserda
Alserda

Reputation: 4744

You could do

const Container = variant === 'rounded' ? Rounded : Flat;

return <Container>{child}</Container>

Upvotes: 2

Related Questions