Search code examples
javascriptreactjslinter

How to fix linter expected to return a value at the end of react function component?


I create a function component to render error message, but its has a linter warning "Expected to return a value at the end of function 'renderErrorMessage' consistent-return

function renderError() {
    if (errors.file) {
      return (
        <Grid item>
          <Grid container direction="column">
            <Grid item>
              <Text size="14px" height="1.43" isError>
                Error Data :
              </Text>
            </Grid>
            {errors.file.map((message) => (
              <Grid item key={message}>
                <Text size="12px" isError>
                  {message}
                </Text>
              </Grid>
            ))}
          </Grid>
        </Grid>
      );
    }
}


Solution

  • Your function will not return any value if errors.file condition is false, thats why you're getting the warning. You can refactor your component like this:

    function renderError() {
      if (!errors || !errors.file) {
        return null;
      }
    
      return (
        <Grid item>
          <Grid container direction="column">
            <Grid item>
              <Text size="14px" height="1.43" isError>
                Error Data :
              </Text>
              </Grid>
              {errors.file.map((message) => (
                <Grid item key={message}>
                  <Text size="12px" isError>
                    {message}
                  </Text>
                </Grid>
              ))}
            </Grid>
          </Grid>
        );
    }