Doubt about React (props or state)

Asked

Viewed 178 times

4

Good afternoon I’m beginner with React, I started reading his documentation and I had a little question: would like to know the difference between prop and state?

And when I know when to use a prop or a state?

If you can give examples, I accept!

  • 1

    If you understand English, this article is excellent: https://kentcdodds.com/blog/props-vs-state

4 answers

1

props = props seriously own such a class or Function, e.g.: I have a prop name in a class/Function person.

state = state serious the state of that class, something you can use that state in different parts of the code, thus reusing it.

I don’t know if I expressed myself very well!

1

State is a variable that can only be manipulated by the component in which it is. If you want another component to also receive this state (for example, for a component with the feature to show the state value), just send it as props.

It is important to note that the component that will receive the props can NOT modify the state values of the other component.

1


Come on, I’ll give you an example and then explain separately ok ? okay

Example

Know in html when you call the img tag created by me

outside the component

<imgMy img="./SUaimg.jpg" CorFundo="red">Seu link</a>

Inside of the component

<div background-Color={this.props.CorFundo}> <img src={this.props.img}/> </div>

On the inside of the component You saw how I’m in charge props.Corfundo and props.img ? outside where I instate the component I call the same names and step parameters, in the case of what would be the background I send a color and what would be the src I would send an image.

State :

    constructor(props) {
    super(props)
    this.state = {
        aberto: true,
    }
}

Let’s say the following I have another component that he expects an open parameter, when true it will open a window asking to log in, let’s see in practice.

<button onclick={() => {this.setState({ aberto: true })}}/>

<JanelaLogar estaAberto={this.sate.aberto}/>

when the open state is changed it will automatically change the parameter that was previously false to true and then the component will be changed also by being connected to the state, something they say is that the state is the state of truth, dynamic things in your app always, case by part not, will be linked to the state.

0

Props are the attributes of your component. The state refers to the state of its component.

Browser other questions tagged

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