Home > Back-end >  React conditional rendering - executes code of alternate condition component
React conditional rendering - executes code of alternate condition component

Time:01-06

Content.js file

import React from 'react';
const Content = () => {
    console.log('content called');
    return (<div>Content</div>);
};

export default Content;

App.js file

import React from 'react';
import Content from './Content';

const App = () => {
const isUserAuthenticated = false;
return (
          <div>
            {
                isUserAuthenticated 
                ? <Content/>
                : <></>
            }
          </div>
    );
}
export default App;

Even though the condition is false, Content component gets loaded and console.log is executed.

Is it because I have imported the file ? I do not see the HTML added to the DOM though.

CodePudding user response:

Can you try this on your App.js :-

import React from 'react';
import Content from './Content';

const App = () => {
const isUserAuthenticated = false;
return (
          <div>
            {isUserAuthenticated  && <Content/>}
          </div>
    );
}
export default App;

CodePudding user response:

I would also go ahead and say you are using it somewhere else, and you haven't noticed. Look through your code!

I put up this sandbox real quick to check it for myself, and the conditional rendering works as expected.
Check if out if you'd like.

  •  Tags:  
  • Related