0

I quickly created this sandbox to explain my problem more easily.

I want that when in click on my clickableItem the value of the input from the simplePopOver component take the value from the state from the clickableItem component.

For that I initialize the state from simplePopOver with a props but the problem is that state is always equal to the init value 'initialisation' whereas the props has the good value (check console.log()). Do you have an idea ? Is it an asynchronous problem ?

I don't think my explanations are clear, but if you check the sandbox it will be more clear :)

johannchopin
  • 13,720
  • 10
  • 55
  • 101

2 Answers2

1

You need to implement getDerivedStateFromProps to update state based on change in props in SimplePopover component

static getDerivedStateFromProps(props, state) {
    console.log(props);
    if (props.clickableElementText !== state.prevClickableElementText) {
      return {
        prevClickableElementText: props.clickableElementText,
        textInInput: props.clickableElementText,
      }
    }
    return {
      prevClickableElementText: props.clickableElementText
    }
  }

Working demo

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • It works perfectly ! Thank you :) It is a good practice to use this method ? – johannchopin Feb 18 '19 at 18:27
  • There are multiple alternatives to getDerivedStateFromProps which you can use depending on your usecase. You can have a look at the documentation for more details. For your use case `getDerivedStateFromProps` is the correct alternative – Shubham Khatri Feb 18 '19 at 18:29
0

the state clickableElementText

it is not declared

Use this.state.textInInput