2

I'm trying to learn react and webpack. I have the following file called Banner2.js with the content:

import React from 'react';

export default class Banner2 extends React.Component{
    render() {

        return (
            <h2>Banner 2</h2>
            {this.showPara()}
        );
    }
    showPara()
    {
        return (<p><span>This is text</span></p>);
    }
}

When I run the webpack command line, I get the error message:

ERROR in ./src/Components/Banner2.js Module build failed: SyntaxError: /var/www/html/wp/src/Components/Banner2.js: Unexpected token (11:3) return (

Banner 2

{this.showPara()} );

What did I do wrong? I just want the output of the showPara() function to show up in the render function.

2 Answers 2

1

The contract for render methods implemented by components that use either ES6 classes or React.CreateClass specifies that you need to return exactly one component. Some of this has to do with there not being multiple returns in JavaScript (as opposed to Go or others where you can return true, 'false' from a function). Trying to return two components alongside each other is like trying to do this:

return(
   React.createElement('div', {}, null), 
   React.createElement('div', {}, null)
 )

Javascript will get upset and throw an error when it sees you trying to do a multiple return.

The other aspect is just the way that React parses element trees and renders them. Trying to return the two alongside each other within one component is kind of like trying to get two nodes to occupy the same space; they can be next to each other, but can't occupy the same 'one-node' space.

So the error is most likely being throw because you're not returning exactly one child:

render() {
   return (
       <div>
        <h2>Banner 2</h2>
        {this.showPara()}
       </div> 
}

(or whatever else you want to wrap it in so exactly one child is returned)

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

Comments

0

I just remembered the return statement can only return one top level tag. So I replaced

    return (
        <h2>Banner 2</h2>
        {this.showPara()}
    );

with

    return (
        <div>
        <h2>Banner 2</h2>
        {this.showPara()}
        </div>
    );

Now things are fine.

1 Comment

Saw you already answered this, but thought I might elaborate a little more for other people trying to figure out the same thing. It's a pretty common error in React and I'm hoping people will better avoid it by understanding by what's actually happening and why you can't just return 2 nodes/components

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.