Alexander Nenartovich
Alexander Nenartovich

Reputation: 826

Rendering a Constant Inside of a React Class Component

I have a quick question regarding the way to render content using constants in a React class component. So the following code works fine (rendering a constant using the map function):

class App extends React.Component {

array = [
   {
      name: "Sarah",
      age: 27
   },
   {
      name: "Sam",
      age: 35
   }
 ]

render() {
  const output = this.array.map(elem => (
      <div>
        <p>{elem.name}</p>
        <p>{elem.age}</p>
      </div>
  ));
    return (
      <div>{output}</div>
    );
  }
} 

However, the following produces a blank page (I am simply defining a constant that returns a div and trying to render it):

class App extends React.Component {

  render() {
    const Output = () => (
        <div>Hello</div>
    );
    return (
      <div>{Output}</div>
    );
  }
}

But virtually identical code works if instead of the curly braces I use the angular ones:

class App extends React.Component {
  render() {
    const Output = () => (
      <div>Hello</div>
    )
    return (
      <div>
        <Output />
      </div>
    )
  }
}

So it seems like this has something to do this curly and angular brackets. Curly braces work when I use a map function but do not when I define a constant that returns a div inside a render method and try to render it directly. Then it works again when I use angular brackets... This is kind of strange. I understand that this is far from the most important thing, I'm just trying to get to the bottom of this. Thank you in advance!

Upvotes: 0

Views: 3913

Answers (2)

Gustaf Lundstr&#246;m
Gustaf Lundstr&#246;m

Reputation: 58

Angular brackets are used to render components. Since you've defined Output as a function which returns some JSX, this makes it a function component as far as React is concerned (or rather Babel, which handles the transpilation of your JSX).

You can use curly brackets but then you should change Output to a React node. Here's how you'd do that:

class App extends React.Component {

  render() {
    const Output = <div>Hello</div>
    return (
      <div>{Output}</div>
    );
  }
}

Check THIS answer for some clarification regarding the difference between React nodes, elements etc.

Upvotes: 1

Anh Tuan
Anh Tuan

Reputation: 1143

class App extends React.Component {

  render() {
    const Output = () => (
        <div>Hello</div>
    );
    return (
      <div>{Output()}</div>
    );
  }
}

if you try to call a function Output() it will return the JSX but follow this article they dont recommend that

Upvotes: 1

Related Questions