-2

When I used props in react Components,I used this.props.name to access name.

this.state = {
    seconds:parseInt(this.props.start)
};

But when I do the same thing in functions [stateless],I get an error:

function Show(props) {
    return (
        <p>Hello {this.props.name}!</p>
    );
}

Why is it so?

Jap Mul
  • 17,398
  • 5
  • 55
  • 66
Savannah Madison
  • 575
  • 3
  • 8
  • 17
  • 1
    Because props are passed in as a parameter, not set as a property. Look at the code you've written, you can see it in the function definition. – jonrsharpe Oct 01 '20 at 07:34
  • because there is no `this` in FunctionComponents, only the passed argement(s) – Thomas Oct 01 '20 at 07:35
  • @AnaSvitlica you have given a clear explanation. Thanks – Savannah Madison Oct 01 '20 at 07:37
  • 1
    Except @AnaSvitlica's explanation isn't 100% correct. `Show` is certainly a react component. Stateless vs stateful is old, dead nomenclature. Class-based components can be stateless and functional components can be stateful. – Drew Reese Oct 01 '20 at 07:44

1 Answers1

1

if name is being passed to Show, then you'd just get it from props.name instead of this.props.name

i.e. if this is happening somewhere:

<div>
  <Show name="The Simpsons" />
</div>

then you can access it like this:

function Show(props) {
  return <p>Hello {props.name}!</p>;
}

or you can destructure the name out of props, like this:

function Show({ name }) {
  return <p>Hello {name}!</p>;
}
ike
  • 11
  • 1
  • 1