Home > Net >  same component with different styles if user is signed in
same component with different styles if user is signed in

Time:11-17

Lets say we have component called Main, iam trying to set up condtion inside of it if user is signed it would have diffent styles, i know it seems easy but iam stuck on it for quit some time. thanks for any ideas i had code like this: code snippet

CodePudding user response:

If all you want to do is change the styles and not the content of the component, rather than having an if statement that renders the same element tree twice (just with different classes), you could use conditionals on the className itself.

  className={`className1 ${sign ? 'className2' : `className3`}`}

  //Or if you want to remove classes based on sign
  className={`className1 ${sign ? 'className2' : ''}`}

Better yet, install the classnames package from npm and you can do something like this:

const aClassname = classNames({ class1: true, class2: sign, class3: !sign });

return <div className={aClassname}></div>

https://www.npmjs.com/package/classnames

CodePudding user response:

The most simplistic solution is to use an ternary operator like below;

export function App(props) {
  const sign = true;
  return (
    <div className="container">
      { sign ? (
        <div>
          <h1>Logged in!</h1>
        </div>
      ) : (
        <div>
          <h1>Guest</h1>
        </div>
      )}
    </div>
  );
}

However, this won't be easy to read when your component / different styles scale in size. What you could do is separate the different styles to their own separate components and use conditional rendering to show them.

export function AuthenticatedMain(props) {
  return (
    <div>
      <h1>Logged in!</h1>
    </div>
  );
}

export function GuestMain(props) {
  return (
    <div>
      <h1>Guest</h1>
    </div>
  );
}

export function App(props) {
  const sign = true;

  if (sign) {
    return <AuthenticatedMain/>
  }
  return <GuestMain/>
}


  • Related