简体   繁体   中英

TypeError: Cannot read property 'url' of null in React

Working with React and styled component.

I am trying a conditional rendering for a logo. In my react component <Header> should only be rendered when there is no logo. Here logo is checked as companies[currentCompanyIndex].logo.url which is from companies array.

 <HeaderContainer>
        <Header>
          {!companies[currentCompanyIndex].logo.url &&
            companies[currentCompanyIndex].name}
        </Header>

        {companies[currentCompanyIndex].logo.url && (
          <Logo
            src={companies[currentCompanyIndex].logo.url}
            alt={`${companies[currentCompanyIndex].logo.url}-img`}
          />
        )}
 </HeaderContainer>

Problem TypeError: Cannot read property 'url' of null . In many cases there will only be name rendered as header and no logo. So data will be null in many cases. Although I have put the condition, still I get the error. How to handle this issue?

Expected Render header only when no logo. When there is logo, ignore header and render logo only.

You are not checking if companies[currentCompanyIndex].logo exists, that why you get this error.

You should have that check both inside Header component and outside (where you render logo)

What you did will only check if logo.url is not undefined. It will not check if it is null. Edit your code as show below:

<HeaderContainer> <Header> {!companies[currentCompanyIndex].logo.url &&  companies[currentCompanyIndex].name} </Header> {companies[currentCompanyIndex].logo.url && companies[currentCompanyIndex].logo.url !== null && ( <Logo src={companies[currentCompanyIndex].logo.url} alt={`${companies[currentCompanyIndex].logo.url}-img`} /> )} </HeaderContainer>

I hope this solves your problem. You also need to check that it is not null apart from being undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM