2

How could this conditional statement be simplified? Return statement is being used multiple times. Could for example ternary operators be used in this case?

Is returning null a proper way to hide Components?

import Item from './Item';

const Component = ({data, onChange}) => {

    if (data) {
        const items = data.map(( item ) => {
            return <Item onChange={ onChange } />
        });

        return(
            <ul>{items}</ul>
        );

    } else {
        return(null);
    }
}

export default Component;
silversurfer
  • 329
  • 1
  • 3
  • 8

2 Answers2

4

Is returning null a proper way to hide Components?

Yes, returning null is a valid return value for a React Component. See this section of the official documentation:

Booleans, Null, and Undefined Are Ignored

false, null, undefined, and true are valid children. They simply don't render.


You could shorten your code a bit though:

const Component = ({data, onChange}) => (
  data && data.length ? <ul>
    {data.map(( item ) => <Item onChange={ onChange } />)}
  </ul> : null
)

Note however that you are not using item inside <Item>. Is that intentional? If so, you can write instead: {data.map(() => <Item onChange={ onChange } />)}

Also note that you need to provide a key property to each <Item>. I have not added that to my snippet, but you can read more about the key prop, here.

Chris
  • 57,622
  • 19
  • 111
  • 137
  • You can also remove the parenthesis around item, since it's a single parameter function. Also, you can remove the return keyword if you're not using a block in an arrow function. – Kraylog Jul 11 '17 at 10:43
  • @NimrodArgov, yes I missed the `return`. Fixed that, thanks. I like keeping the parenthesis, but that's just a personal preference. – Chris Jul 11 '17 at 10:47
2

I didn't get to run it so there may be a bug in there somewhere, but would something like this be suitable?

const Component = ({data, onChange}) => {

  function returnItems(data){
    data.map(( item ) => <Item onChange={ onChange } />
    return(<ul>{items}</ul>);
  }

  const items = data ? returnItems(data) : null;
}
ConorJohn
  • 637
  • 2
  • 11
  • 24