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,517
  • 21
  • 66
  • 139
  • 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
  • 132,000
  • 20
  • 149
  • 151
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
  • 15,032
  • 5
  • 31
  • 53