Home > Back-end >  How do I properly write with ?. in a JSX File
How do I properly write with ?. in a JSX File

Time:10-25

I have some code that creates a react component:

const MyMessage = ({ message }) => { 
if(message?.attachments?.length > 0){
    // We have an image
    return(
        <img
            src={message.attachments[0].file}
            alt="message-attachment"
            className='message-image'
            style={{ float: 'right' }}
        />
    )
}}

I get the following error pointing to the ?. syntax

react_devtools_backend.js:4026 
        
       Error in ./src/components/MyMessage.jsx
Syntax error: C:/Users/GitHub/react_chat_app/src/components/MyMessage.jsx: Unexpected token (4:15)

When I remove the ?. and replace with

if(message.attachments.length > 0)

it works fine. What is wrong with my syntax when using ?.?

CodePudding user response:

Length wouldn't be 0 it would be undefined or null. Try:

const MyMessage = ({ message }) => { 
if(message?.attachments !== undefined){
    return(
        <img
            src={message?.attachments[0].file}
            alt="message-attachment"
            className='message-image'
            style={{ float: 'right' }}
        />
    )
}}

CodePudding user response:

While DarthVader's answer is far better, I would like to provide another solution here. You can use ?? operator in addition to check if a value is null or undefined and assign a default value to avoid error if it is.

Example:

const message = undefined;
//const message = {"attachments": [1,2,3]};

const baz = message?.attachments?.length ?? 0;
//console.log(baz);

if(baz > 0){
    // We have an image
    console.log(baz);
}
  • Related