CrashXVII
CrashXVII

Reputation: 31

Conditional render works in stateless functional component but not in stateful

I am converting a stateless functional component into a stateful component. Conditional rendering that works fine in the stateless version creates a parsing error in the stateful version.

This code works:

const Milestone = ({ milestone }) => (
  <div>
    {milestone.displayProperties.hasIcon
  && <Img src={`https://www.bungie.net${milestone.displayProperties.icon}`} alt="Milestone Icon" />
  }
    <p>{milestone.displayProperties.name}</p>
    <p>{milestone.displayProperties.description}</p>
  </div>
);

This code gets me a Parsing error (or various other errors when I've tried other ways to write the "if" statement)

  render() {
    const { milestone } = this.props;
    return (
  <div>
    {milestone.displayProperties.hasIcon
  && <Img src={`https://www.bungie.net${milestone.displayProperties.icon}`} alt="Milestone Icon" />
  }
    <p>{milestone.displayProperties.name}</p>
    <p>{milestone.displayProperties.description}</p>
  </div>
    );
  }

I've tried writing it with different forms of "if" statements. The closest I've gotten is with

{condition ? <Img /> : null}

but it breaks as soon as I add src={...string literal}

The Img tag is a styled component.

The above code worked great as a stateless. Even if the answer is a simple rookie mistake, I'd love to know what I'm not grasping about JSX that causes this mistake.

EDIT: This may just be an issue with ESLint? I should've tested the site first, because everything seems to render fine in browser.

Upvotes: 3

Views: 1543

Answers (1)

Prabu samvel
Prabu samvel

Reputation: 1223

Try this.

<div>
 {
  milestone.displayProperties.hasIcon 
  ? <Img src={`https://www.bungie.net${milestone.displayProperties.icon}`} alt="Milestone Icon" />
  :<span>No Icon found!</span> 
 }
 <p>{milestone.displayProperties.name}</p>
 <p>{milestone.displayProperties.description}</p>
</div>

Upvotes: 2

Related Questions