0

I have a problem about implementing conditional rending in return part of functional component.

I got this kind of error shown below.

Cannot convert undefined or null to object

While some links have more than one link, others have only one link.

How can I fix my issue?

Here is my code shown below.

{Object.keys(projectDialog?.links).length > 1 ? (

                projectDialog?.links 
                  .map((link, index) => (
                      <a href={link.link} target="_blank" key={index} className="projectDialog_icons">{link.icon}</a>
                ))
              ) : (
                <a href={projectDialog?.links.link} target="_blank" className="projectDialog_icons">{projectDialog?.links.icon}</a>
              )
            }
2
  • The error you are getting is from this part of the code Object.keys(projectDialog?.links). projectDialog or projectDialog?.links is undefined or null. Commented Jul 18, 2022 at 20:13
  • probably on initial render you pass projectDialog which is null at that time - just add another conditional rendering over current render: projectDialog ? <render links> : <render placeholder> Commented Jul 18, 2022 at 20:47

1 Answer 1

1

You need additional check for cases if projectDialog or projectDialog?.links are null or undefined, for better readability and prevent from nested ternary conditional rendering I would write in such way:

...
if (!projectDialog || !projectDialog?.links) return null;
//after above check you can be sure that below return will be with defined values
return (
 {Object.keys(projectDialog?.links).length > 1 ? (
    projectDialog?.links.map((link, index) => (
       <a href={link.link} target="_blank" key={index} className="projectDialog_icons">{link.icon}</a>
                ))
              ) : (
                <a href={projectDialog?.links.link} target="_blank" className="projectDialog_icons">{projectDialog?.links.icon}</a>
              )
            }
)
Sign up to request clarification or add additional context in comments.

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.