C
C
cester2018-03-16 15:32:01
JavaScript
cester, 2018-03-16 15:32:01

How to update state child-a from parent component, react?

Good afternoon! Please tell me how to update the state child from the parent in react if child is displayed in a loop?
Will he change in this case?
Component Example

export default class ParentBlock extends Component {
  static propTypes = {
    blocks: PropTypes.arrayOf(PropTypes.object),
  };

  render() {
    const { blocks } = this.props;
    return (
      <ParentBlocksList blocks={blocks} />
    )
  }
}

const ParentBlocksList = ({
  blocks,
}) => (
  <div>
    {blocks.map(block => (
      <ParentBlockItem
        key={block.id}
        name={block.name}
        values={block.values}
        disabled={block.disabled || false}
      />
    ))}
  </div>
);

const ParentBlockItem = ({
  name,
  values,
  disabled,
}) => (
  <div>
    <table>
      <tbody>
        {Object.entries(values).map(([name, val]) => (
          <ChildBlockItemRow
            key={name}
            name={name}
            value={val}
            disabled={disabled}
          />
      ))}
      </tbody>
    </table>
  </div>
);

export default class Child extends Component {
  static propTypes = {
    name: PropTypes.string,
    value: PropTypes.string,
    disabled: PropTypes.bool,
  };

  state = {
    value: this.props.value,
  };

  handleChange = (e) => {
    const { value } = e.target;

    this.setState({
      value,
    });
  };

  render() {
    const { name, disabled } = this.props;
    const { value } = this.state;

    return (
      <tr>
        <td>{name}</td>
        <td>
          <input
            type="text"
            value={value}
            onChange={this.handleChange}
            disabled={disabled}
            ref={(el) => {
              this.input = el;
            }}
          />
        </td>
      </tr>
    );
  }
}

It is necessary that the Child is updated from the ParentBlock of the component.
Please tell me what is the solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-03-16
@maxfarseer

Well, just as always, you change the blocks - it turns out there is a redrawing.
To get rid of unnecessary redraws, if such nesting cannot be changed, then add the shouldComponentUpdate hook

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question