0

I have a first code that looks like this, it's a console list with on / off buttons:

const ConsoleDisplay = () => {
  const statusData = useContext(StatusDataContext);
  const [open, setOpen] = useState(false);
  const [oneConsoleDataIndex, setOneConsoleDataIndex] = useState();

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <Fragment>
      {statusData.map((data, index) => {
        const handleOpen = () => {
          setOpen(true);
          setOneConsoleDataIndex(index);
        };

        const displayBtnStatusOncycle =
          !timesUp &&
            (data['cycle in progress 1'] || //boleen
              data['cycle in progress 2'])
            ? 'var(--btn-green)'
            : 'var(--btn-grey)';

        const displayBtnStatusOffcycle = timesUp
          ? 'var(--btn-red)'
          : 'var(--btn-grey)';

When I click on one of the consoles, it opens a modal that I can close. At the top right, I can switch consoles without closing the window by clicking on another console. In this modal, I have the same information in a new component:

const ConsoleDetails = ({ setIndex, index, open, close }) => {
    const statusData = useContext(StatusDataContext);
    const data = statusData[index];
    
    return (  
      <Card
        onClick={() => setIndex(i)}
      >
       <span>
       {data && data.console_nickname
        ? data.console_nickname
        : data && data.console_id}
       </span>
      </Card>
      const displayBtnStatusOncycle =
        !timesUp &&
        data &&
        (data['cycle in progress 1'] || //boleen
          data['cycle in progress 2'])
          ? 'var(--btn-green)'
          : 'var(--btn-grey)';
    
      const displayBtnStatusOffcycle = timesUp
        ? 'var(--btn-red)'
        : 'var(--btn-grey)';

There is something I don't understand, why use data && (data['cycle in progress 1'] in the second component instead of (data['cycle in progress 1']? or just {data.console_nickname ? data.console_nickname : data.console_id} ? Why use data &&?

1
  • So that you wont get an error when data is null or undefined. Commented Aug 17, 2021 at 21:24

2 Answers 2

3

Let's assume for a moment that statusData[index] does not exist, and data is therefore undefined. If you would then use the snippet you are proposing:

data.console_nickname

That would evaluate to

undefined.console_nickname
// Uncaught TypeError: Cannot read property 'console_nickname' of undefined

If you would however prepend it with data &&, the statement would evaluate to

undefined && undefined.console_nickname

Written like this, the first half of the operation evaluates to false (undefined is falsy) and prevents the second half of the statement to be run. This is only necessary when you want to access a property on an object that might be undefined.

Optional chaining (ES2020)

A recent addition to the JavaScript language is optional chaining. It allows you to access a property of an object that might be undefined:

data?.console_nickname

If data is now undefined, the entire statement will evaluate to undefined without throwing an error. Depending on your use case, this can replace the data && trick mentioned before.

If needed, you can even chain these lookups like this:

data?.propOne?.propTwo?.propThree

If any of these props down the line is undefined, the entire chain evaluates to undefined. This makes it very safe and easy to traverse deep inside your data.

Beware that this is a recent addition to the language, and although all major browsers do already support it you should check it with your project. Since you're using React, your code will probably already be preprocessed anyway and language features like this usually get translated to versions that are compatible with older browsers.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your comment, I understand much better, however, this operator could have been applied also in the first component?
If you're talking about the optional chaining: you can also use it like data?.['cycle in progress 1'] when you need to use square brackets. I just wanna note that there is nothing wrong with using data &&, as described in the docs @CodeoftheWarrior linked to in his answer.
0

https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator

The above comment by Daemes is correct, but it's good to go to documentation and realize the react team recommends this form of conditional rendering.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.