React does not render the result of this code

Asked

Viewed 396 times

1

I am studying React and I have a problem, more precisely in the state part, where my code does not render on the screen. In this case I have a h1 and a ul and none of them appear on the screen, but if I delete the h1 appears the ul, and if I delete the ul appears the h1.

Code

class App extends React.Component {
  constructor(props) {
    super(props);
    this.team = {Tname: "Dev's React"},
    this.names = {member1 : 'Caua', member2: 'Luna', member3: 'Henry', member4: 'Barry'}
  }


  render(){
    return (
      <h1>Hello Team {this.team.Tname} </h1>
      <ul>
        <li> Member 1: {this.names.member1} </li>
        <li> Member 2: {this.names.member2} </li>
        <li> Member 3: {this.names.member3} </li>
        <li> Member 4: {this.names.member4} </li>
      </ul>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

1 answer

3


This is happening because each component of React can only render a son at a time. If you notice your code, the component App is trying to return two elements at once: h1 and ul - which are "adjacent" in the code.

You then need to wrap these two components in one. To do this, you can, for example, use a simple <div>. An alternative, better, is to use the React.Fragment, that will not print any element in the DOM, serving only to involve multiple components in one.

function App() {
  return (
    <React.Fragment>
      <h1>Title</h1>
      <ul>
        <li>Lista</li>
      </ul>
    </React.Fragment>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>


As a final remark, it is worth saying that you are setting your state incorrectly. Within components-class, its state must be placed inside the object this.state, and not in the instance itself (as you are doing). To learn more, read the state guide of the React documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.