F
F
faleaksey2019-01-15 16:22:23
React
faleaksey, 2019-01-15 16:22:23

How to forward data to State?

Hello! above, I left the question of the implementation of such a component. How to implement the "Save" component? .
After sitting for a bit, I managed to do the following, but I don’t fully understand how to change the main state (or rather the product property in state)
of the parent component with state:

import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';

import Product from '../../components/Product/Product';



class MainPage extends Component {
  state = {
    savedProducts: [],
    products: [
      {
        id: 1,
        title: 'Product One',
        saved: false
      },
      {
        id: 2,
        title: 'Product Two',
        saved: true
      },
      {
        id: 3,
        title: 'Product Three',
        saved: false
      }
    ]

  };

  likeHandler = (id) => {
    console.log(id);
    const idProduct = this.state.products[id - 1].saved;
    console.log(idProduct);

  }
  renderProduct() {
    return this.state.products.map((info, index) => {
      return (
        <Product
          key={index}
          inform={info}
          id={info.id}
          saved={info.saved}
          likeToggle={this.likeHandler}
          />
      )
    })
  }
  render() {
    return (
      <div>
        {this.renderProduct()}
      </div>
    )
  }
}

export default MainPage;

child component with button:
import React, { Component } from 'react';



class Product extends Component {

  render() {
    return (
      <div>
        {this.props.inform.title}


        <button
          className={this.props.saved ? 'like-button liked' : 'like-button'}
          onClick={() => this.props.likeToggle(this.props.id)}>Like</button>
      </div>
    )
  }
}
export default Product;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-01-15
@faleaksey

likeHandler = (id) => {
  this.setState(({ products }) => ({
    products: products.map(n => n.id === id
      ? { ...n, saved: !n.saved }
      : n
    ),
  }));
}

A
alexhovansky, 2019-01-15
@alexhovansky

setState doesn't work?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question