Ad

(ReactJs) How Include More Than One Component In Another Component?

- 1 answer

Edit: This has been solved. In Menu.js I had written "export default MenuChoise;".

I´m new to React. To me, the code below should produce 2 buttons, one with the text "Show content" and the other with the text "Add new book". Instead I get one button with no text at all. Why?

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import Menu from './pages/Menu';

ReactDOM.render(
  <Menu text1="Show content" text2="Add new book"/>,
  document.getElementById('app')
);

Menu.js:

import React from 'react';
import MenuChoise from './MenuChoise';

class Menu extends React.Component {
    render() {
        return
          (<div>
            <MenuChoise choisetext={this.props.text1}/>
            <MenuChoise choisetext={this.props.text2}/>
          </div>);
    }
}

export default MenuChoise;

MenuChoise.js:

import React from 'react';

class MenuChoise extends React.Component {
    render() {
        return(
          <button type="button" value={this.props.choisetext}/>
        );
    }
}

export default MenuChoise;
Ad

Answer

The render method for your Menu component is returning undefined because you've placed the opening parenthesis after the return on the next line.

class Menu extends React.Component {
  render() {
    return
      (<div>
        <MenuChoise choisetext={this.props.text1}/>
        <MenuChoise choisetext={this.props.text2}/>
      </div>);
  }
}

Before the browser evaluates your code, it passes through a transformation called Automatic Semicolon Insertion (ASI), where it tries to work out where there should where to terminate lines of code.

In this case, the ASI adds a semicolon after return, which causes the function to terminate without a return value.

  render() {
    return; // <-- asi happens here
      (<div>
        <MenuChoise choisetext={this.props.text1}/>
        <MenuChoise choisetext={this.props.text2}/>
      </div>);
  }

There's no way for React to know what happened here, so it can't tell you what the problem was, however, the error message would have been:

Uncaught Error: Invariant Violation: Menu.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

This will at least help you understand where the problem is coming from.

Ad
source: stackoverflow.com
Ad