0

I moved the selectedProduct to the Products component. Then I added new values to properties selectedProduct. How can I return this object to the component App to the products array?

App

class App extends Component {
  constructor(){
    super();

    this.state {
      products: [  
            {
                color: ['black', 'orange']
                desc: 'gfgfg'
            },
            {
                color: ['yellow'],
                desc: 'gfgfgfg'
            }
        ]
    }

  }

  add = (updateProduct) => { 
    const {products} = this.state; 
    this.setState({ 
        products: [...products, updateProduct] 
    }) 
  }


  render () {
    let selectedProduct = this.state.products[0];

    return (
      <div>
        <ul>
            {
                this.state.products
                .map((product, index) =>
                    <Product
                        key={index}
                        index={index}
                        product={product}
                    />
                )
            }
        </ul>
          <Products
            selectedProduct = {selectedProduct}
            add={this.add}
          />
      </div>
    )
  } 
}

export default App;

Products

class Products extends Component {
    constructor(){
        super();

        this.state = {
            selectProduct: [{
                color: ['black', 'orange', 'pink]
                desc: 'gfgfg'
            }]
        }
    }

    componentDidUpdate (prevProps) {
        if (prevProps.selectedProduct !== this.props.selectedProduct) {
            this.setState({
                selectProduct:  this.props.selectedProduct
            });
            if (this.props.add) {
                this.props.add(this.state.selectProduct) 
            }
        }
    }

  render () {
    return (
      <div>
      </div>
    )
  } 
}
Umbro
  • 1,984
  • 12
  • 40
  • 99

1 Answers1

1

You need to propagate the changes back to App, in your case you could set up a changeState function in the parent component and propagate it down as a property. See here for more information How to update parent's state in React?

There are multiple options, I would recommend using hooks and the Context API though, example: https://upmostly.com/tutorials/how-to-use-the-usecontext-hook-in-react/

wfreude
  • 492
  • 3
  • 10