Search code examples
reactjstypescriptsession-storage

React checking multiple conditions to render a component


I would like to check the sessionStorage and check another variable set by state before rendering a component. Basically if the user already acknowledges reading a message I would like to not show it anymore within the same session, so my code looks like this:

const addSession = (noteId: string) => {
  sessionStorage.setItem(noteId, noteId); 
}

const message = (props: ImessageProps) => {
  const [addedInSession, setAddedInSession] = useState(false); 
  return (
     <div>      
     {props.messages.map(m => {
        return (
        {!addedInSession && sessionStorage.getItem(noteId) && <MyComponent />}
         )
      })}
      </div>
  )}

However am having an error when I do the !addedInSession it's telling me ')' is expected. If I remove the !, then it will give an error on the first && saying ',' is expected.

What am I doing wrong here?


Solution

  • return (
      {!addedInSession && sessionStorage.getItem(noteId) && <MyComponent />}
    )
    

    In this code, you're not inside any JSX, so you don't need to use curly brackets to escape back into regular javascript/typescript. So simply drop the curly brackets and you'll fix the syntax error:

    return (
      !addedInSession && sessionStorage.getItem(noteId) && <MyComponent />
    )