javascript – How do I create a multi-line component?

Question:

There is such a component

function Person(props){
  return (
    <div>Name: {props.name} {props.surname}</div>
    <div>Age: {props.age}</div>
  );
}

It does not appear when rendering.

const element = <Person name="Иван" surname="Иванович" age="47"></Person>;
ReactDOM.render(element, document.getElementById('app'));

But when we leave one block, everything works.

function Person(props){
  return <div>Name: {props.name} {props.surname}</div>;
}

Why?

Answer:

If the reagent is new enough, then fragments should be used. And if it's old, then nothing.

function Person(props) {
  return <React.Fragment>
    <div>Name: {props.name} {props.surname}</div>
    <div>Age: {props.age}</div>
  </React.Fragment>
}

const element = <Person name="Иван" surname="Иванович" age="47"></Person>;
ReactDOM.render(element, document.getElementById('app'));
<script src="//cdnjs.cloudflare.com/ajax/libs/react/16.4.1/umd/react.production.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.1/umd/react-dom.production.min.js"></script>

<section id="app"></section>

In theory, a shorter syntax should be available for fragments, but it did not work in the snippet (perhaps the babel is outdated):

function Person(props) {
  return <>
    <div>Name: {props.name} {props.surname}</div>
    <div>Age: {props.age}</div>
  </>
}
Scroll to Top
AllEscort