Home > Mobile >  How to render two const components in a conditional case in React JS?
How to render two const components in a conditional case in React JS?

Time:12-17

I have declared 2 constant components in my React functional component. I am trying to render them based on a condition,

      <Flex.Box w="90px" ml={1}>
        { mycondition
          ? ({ staticButton })
          : ((
            { staticButton })({ conditionalButton }))}
      </Flex.Box>

I am trying to render based on if mycondition is true or false. But, I am getting the below error in the console.

TypeError: {(intermediate value)} is not a function

Am I doing anything wrong?

CodePudding user response:

When you want to render 2 components at the same time in a ternary, you should wrap them inside a fragment (<>{staticButton} {conditionalButton}<>). I guess your 2 const are components pass by props ?

CodePudding user response:

It seems you can move the staticButton out of condition:

<Flex.Box w="90px" ml={1}>
  {staticButton}
  {mycondition ? conditionalButton : null}
</Flex.Box>

CodePudding user response:

You can't really do what you're asking here.

  1. If you're creating components inside another component you still have to use Pascal Case.

  2. You still need to wrap the component name in < />. You can't just return a function.

  3. Adjacent components need to be in a container.

function Example() {

  const condition = false;

  const StaticButton = () => <div>Static</div>;
  const ConditionalButton = () => <div>Conditional</div>;

  return (
    <div>
      {condition
        ? <StaticButton />
        : (<div>
            <StaticButton />
            <ConditionalButton />
          </div>)
       }
    </div>
  );
};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related