lundi 10 décembre 2018

Keep the state in child and update parent

I am writing my own react-table component. The table should receive an array of objects that will work as 'rows'. Each row may have a prop called 'subrows'. In this way, I can handle any levels of depth. When I right click in any row a few modal options appear in the screen (Similiar to a youtube video). These options will vary based on the table use but there are a few ones that are similar in all tables such as 'Add row', 'Delete row', etc.

My first thought was to hold the state in a Container component and pass the rows as a prop to the Table component and handle all CRUD operations in the Container. This means that I will need to implement 'onAddRow', 'onDeleteRow' in every Container that may have a Table.

The solution I came with was to keep the state in both places, Table and Container. Implement the logic to delete a row in the Table component and just let know the Container that a row has been deleted so it may or may not handle it.

import React from 'react'

export default class Container extends React.Component {

  constructor(props){
    super(props)
    this.state = {
      rows: []
    }
  }

  deleteRowHandler = row => {
    /* 
      Update container state and may call the API
    */
  }

  render(){
    return (
      <Table
        rows={this.state.rows}
        onDeleteRow = {deleteRowHandler}
      />
    )
  }
}

export default class Table extends React.Component {

  constructor(props){
    super(props)
    this.state = {
      rows: this.props.rows
    }
  }

  deleteRow = () => {
    /* 
      Code to delete the row from the Table state 'rows'
    */
    if(this.props.deleteRow){
      this.props.deleteRow(row)
    }
  }

  render(){
    /* 
      Render the table based on Table state 'rows'
    */
  }
}

Am I implementing an anti-pattern here? Any better ideas?

Aucun commentaire:

Enregistrer un commentaire