I want to make a conditional component in React but didnt work, What am I doing wrong?

22 hours ago 1
ARTICLE AD BOX

If you do this:

<Parent> <Child a={thing.a} /> </Parent>

then a tree of components is created (Parent and Child). The props for Child are all gathered and evaluated as part of creating the tree, so thing has to have a value because Child is unconditionally part of the tree.

This happens before any rendering takes place. It makes no difference if Parent then decides not to render its children.


As an aside, this is how I would do this in my code - no extra component and only an && between the boolean logic and the component code:

{(users.length > 0 && pagination) && <Pagination sx={{ mt: '1rem' }} page={page} count={pagination.last_page} onChange={handleChangePage}/> )}

If the part before the && is false (or false-ey) then the part after it is never evaluated. The result of the whole is then also false (or false-ey) and React does not render anything for that.

Also you never need empty fragments (<></>), to me they are just noise that is to be avoided. If you feel you must put something there, then you should use null.

Peter B's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article