2

I have the following component:

export const Checkmark = props => (
  <Layout {...props}>
    { 
      if(props.checked){
        <Icon name="checkmarkBlue" small />
      } 
    }
  </Layout>
)

my linting is complaining about the "if" saying (unexpected token)

enter image description here

Aessandro
  • 5,079
  • 17
  • 60
  • 122
  • There's [an entire page about this in the docs](https://reactjs.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator). – Jordan Running Feb 22 '18 at 15:57

2 Answers2

4

Inside the brackets there must be expressions. You could change it to a ternary:

  { props.checked ? <Icon name="checkmarkBlue" small /> : "" }

Alternatively if you really need statements, you might use an IIFE

{(function(){
  if(props.checked)
    return <Icon name="checkmarkBlue" small />;
  //...
  return "";
})()}
Jonas Wilms
  • 120,546
  • 16
  • 121
  • 140
1

From React#github

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction

you should use short-circuit instead.

<Layout {...props}>
    {     
      props.checked && <Icon name="checkmarkBlue" small />     
    }

Or

   render(){

      let myHtml = "";

      if(props.checked){
        myHtml = <Icon name="checkmarkBlue" small /> 
      }

      return (<Layout {...props}> { myHtml}</Layout>);
    }
RIYAJ KHAN
  • 14,597
  • 5
  • 30
  • 52