copenndthagen
copenndthagen

Reputation: 50732

React control rendering of the child components dynamically

I have a parent React component and it has child components rendered within it.

<div id="parent">
    {<div style={{ visibility: isComp1 ? "visible" : "hidden" }}><MyComponent1 {...props}/></div>}
    {<div style={{ visibility: isComp2 ? "visible" : "hidden" }}><MyComponent2 {...props}/></div>}
    {<div style={{ visibility: isComp3 ? "visible" : "hidden" }}><MyComponent3 {...props}/></div>}
</div>

At a time, only one of the components would be rendered to the screen, depending on clicks to links on main parent page Link1/2/3. I control the visibility based on isComp1/2/3

Now within these child components, I have some API calls. I only want those API calls to be triggered when the respective links are clicked (i.e. Link1/2/3). However, I observe that despite setting the visibility to 'none' by default, all the 3 child components are rendered and all the child API calls are getting triggered.

Am I doing something wrong by using the visibility attribute ?

Upvotes: 1

Views: 38

Answers (2)

lpizzinidev
lpizzinidev

Reputation: 13289

You can use conditional operators to hide/show the corresponding component:

<div id="parent">
    {isComp1 && <div><MyComponent1 {...props}/></div>}
    {isComp2 && <div><MyComponent2 {...props}/></div>}
    {isComp3 && <div><MyComponent3 {...props}/></div>}
</div>

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191946

The component is called and rendered, and the api calls are executed. The visibility CSS property only effects the appearance of the DOM element on the page.

Use conditional rendering instead:

<div id="parent">
  {isComp1 && <MyComponent1 {...props}/>}
  {isComp2 && <MyComponent2 {...props}/>}
  {isComp3 && <MyComponent3 {...props}/>}
</div>

Upvotes: 1

Related Questions