Ad

React Custom Component(DataTable)

im new to react and im trying to build a custom componenet with parameters.

Im just wonding whats the exact way on doing it.

Here is my current code, how should i pass those Columns,ajax and datasource to the componenet. Or im i doing it wrong?

import * as React from 'react';
interface Column {
    name: string,
    header: string,
    value: Function
}
export default class DataTable extends React.PureComponent<({
    dataSource: any[],
    ajax: string
    columns: Column[]
    onEdit: Function,
    onDelete: Function
})>{

    public state = {
        dataSource: [],
        ajax: undefined,
        columns: [],
        onEdit: undefined,
        onDelete: undefined
    }

    componentDidMount() {
        if (this.state.ajax != undefined) {
            fetch(this.state.ajax)
                .then(response => response.json())
                .then(data => this.setState({ dataSource: data }));
        }
    }

    render() {

        var template = (
            <table className="table">
                <thead className="thead-darked">
                    {
                        this.state.columns.map((x: Column) => {
                            <th scope="col">{x.header}</th>
                        })
                    }
                </thead>

            </table>)
        return template;
    }
} 
Ad

Answer

  1. You don't need ajax, columns, onEdit, and onDelete state. Just use the props.
  2. Initialize this.state.dataSource with this.props.dataSource.

Two changes above will resolve your problem. Additionally,

  1. You may want to fetch the data again if ajax prop changes. You have to implement componentDidUpdate method for the behavior. However, I recommend making a function component and using useEffect hook.
  2. Your dataSource state won't be updated if dataSource prop changes. It can lead to a buggy behavior though you can add more code to avoid bugs. If you move the "ajax" part outside of the component and only use dataSource prop, the logic will be clearer and less bug-prone.

Below is the updated code.

interface Props {
    dataSource: any[],
    ajax: string,
    columns: Column[],
    onEdit: Function,
    onDelete: Function
}

export default class DataTable extends React.PureComponent<Props>{
  public state = {
    dataSource: this.props.dataSource,
  }

  componentDidMount() {
    if (this.props.ajax != undefined) {
      fetch(this.props.ajax)
        .then(response => response.json())
        .then(data => this.setState({ dataSource: data }));
    }
  }

  render() {
    const template = (
      <table className="table">
        <thead className="thead-darked">
          {
            this.props.columns.map((x: Column) => {
              <th scope="col">{x.header}</th>
            })
          }
        </thead>
        {/* render something with this.state.dataSource */} 
      </table>
    );
    return template;
  }
} 
Ad
source: stackoverflow.com
Ad