DEV Community

Discussion on: Simplify condition rendering in React.js

Collapse
 
hedwardd profile image
Heath Daniel

Interesting. Can you explain further? They are rendered by the parent component but the 'IF' component just controls whether they are displayed or not?

Collapse
 
baronw profile image
Baron Willeford

Correct. ‘IF’ and the child are rendered from the same place. The ‘children’ prop is just a reference, is not actual call site. To actually prevent it from being rendered, you would want to call the conditionally rendered component from the ‘IF’.

Thread Thread
 
hedwardd profile image
Heath Daniel

I'm not sure if this is a good way to test but I tried testing it by creating a component that logs to the console when it renders and it looks like that code never ran.

Link to CodePen: codepen.io/hedwardd/pen/xxdOpxy?ed...

Could it have something to do with it being a functional component?

Thread Thread
 
lfbergee profile image
Leiv Fredrik Berge

Exactly, this will actually add the child node to the tree and perform any effects for example. You can avoid this by using render props, but that kinda defeats the purpose.

Thread Thread
 
hedwardd profile image
Heath Daniel

Does it? Now I'm confused. If you look at the CodePen I created, the effects don't seem to run (unless I'm misunderstanding something)

Thread Thread
 
rmurati profile image
Redžep Murati

Actually it shouldn't run. I've created a codesadbox for you guys to check out where you can see both functional and class based components.
Here is the link:
codesandbox.io/s/nice-wiles-cwfi6?...