user3438917
user3438917

Reputation: 497

React.js - Receiving error "Nothing was returned from render." from switch statement

Given a component which takes in a prop and should render a piece of markup depending on the block.type value, I'm receiving the error

Error: Paragraph(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null..

What am I missing in my render I can't get the paragraph to render?

const Paragraph = props => {
    const { block  } = props;
    const align = block.attributes.align;
       switch (block.type) {
          case 'CORE_PARAGRAPH':
            if (align === 'center') {
                return (
                    <div style={{ textAlign: align }}>
                        <div>
                            <p
                                dangerouslySetInnerHTML={{ __html: block.innerHtml }}
                            />
                        </div>
                    </div>
                );
            }
            break;
          default:
            break;
        }
 };

Upvotes: 1

Views: 290

Answers (2)

Augusto Henrique
Augusto Henrique

Reputation: 238

If your component don't need to return a "html", think about returning null on default in switch, like this:

const Paragraph = (props) => {
  const { block } = props;
  const align = block.attributes.align;
  switch (block.type) {
    case "CORE_PARAGRAPH":
      if (align === "center") {
        return (
          <div style={{ textAlign: align }}>
            <div>
              <p dangerouslySetInnerHTML={{ __html: block.innerHtml }} />
            </div>
          </div>
        );
      } else return null;
    default:
      return null;
  }
};

Upvotes: 2

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Create a variable called content and update inside the switch cases then return it :

const Paragraph = props => {
    const { block  } = props;
    const align = block.attributes.align;
  
  let content=null;

       switch (block.type) {
          case 'CORE_PARAGRAPH':
            if (align === 'center') {
                content= (
                    <div style={{ textAlign: align }}>
                        <div>
                            <p
                                dangerouslySetInnerHTML={{ __html: block.innerHtml }}
                            />
                        </div>
                    </div>
                );
            }
            break;
          default:
             content=null
            break;
        }

return <>{content}</>
 };

Upvotes: 1

Related Questions