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;
2
  • Return early. Take the return out of the else, stick it at the top inside an if(!data) and then remove the other if statement. Commented Jul 11, 2017 at 10:33
  • Simplified? Hardly. Shortened? Sure, as usual. Commented Jul 11, 2017 at 10:35

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@NimrodArgov, yes I missed the return. Fixed that, thanks. I like keeping the parenthesis, but that's just a personal preference.
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.