0

I have a question: I have a custom onClick and onChange functions I want included into the selection checkboxes

How can I achieve that? So that when someone selects a checkbox generated from MT they run the custom onClick and onChange?

also wondering about possibility of adding a autofill for the search bar?

ie you start typing and it gives you values that matches what is in the data or top 5 values or something in the data and allows the user to fill out the autofill by clicking the dropdown options.


  state = {
    items: [],
    chosen: [],
    selected: []
  }

  toggle = (id) => {

    const selected = this.state.selected;

    if (selected.includes(id)) selected.splice(selected.indexOf(id), 1); else selected.push(id);

    this.setState({ selected });
    localStorage.setItem('chosen', JSON.stringify(selected));

    console.log(this.state)

  }

  async componentDidMount() {

    this.setState({
      items: await (await fetch(`${process.env['REACT_APP_API']}/items`)).json(),
      selected: JSON.parse(localStorage.getItem('chosen')) || []
    }); 

  }

render() {
return (

<Fragment>
 <MaterialTable
  columns={[
    { 
      title: 'myChecbox',
      render: rowData => {
        return (
          {/* THIS WORKS AS IT SHOULD  */}
          <input className="toggle_checkbox toggle" type="checkbox" checked={this.state.selected.includes(rowData.id)} onChange={this.toggle.bind(this, rowData.id)} />
        )
      },
      cellStyle: {
        width:20,
        maxWidth:20,
        padding:20
      },
      headerStyle: {
      width:20,
      maxWidth:20,
      padding:20
      }
    },
    { 
      title: 'Logo', field: 'name',
      render: rowData => {
        return (

          <a href={rowData.link} key={rowData.id}>
            <img className="image" src={rowData.logo} alt={rowData.name} />
          </a> 
        )
      }
    },
    { 
      title: 'Name', field: 'name',
      render: rowData => {
        return (

          <a href={rowData.link} key={rowData.id}>
            <div className="NameContainer">
              <h5>{rowData.name}</h5>
              <span>{rowData.type}</span>
            </div>
          </a>

        )
      }
    },
    { 
      title: 'score', field: 'score', 
      cellStyle: data => {
        if (data === "N/A") {
          return {
            color: "#aaa",
          }
        }
      } 
    },
    { title: 'Size', field: 'size' },
  ]}

  data=
    {
      this.state.items.length ? this.state.items.map((item) => (
        { 
          id: item.id,  
          logo: item.Logo.url, 
          name: item.Name,
          type: item.Type.replace(/_/g, ' '),
          score: item.Score, 
          size: item.Size
        }
      )) : [{ name: 'LOADING' }]
    }

  options={{
    maxBodyHeight: 1000,
    grouping: true,
    selection: true,
    pageSize: 10,
    doubleHorizontalScroll: true,

  }}

{/* I CANT GET THIS TO WORK =/ */}
  onRowClick={(event, rowData) => { this.state.selected.includes(rowData.id); }}
  onSelectionChange={data => {this.toggle.bind(this, data.id)}}
 />
</Fragment>

);
}
});
Jared Forth
  • 1,577
  • 6
  • 17
  • 32

3 Answers3

0

onSelectionChange pass an array of selected rows. So data parameter has not an id.

for auto complete of search field you can open an feature request issue on github.

mehmet baran
  • 636
  • 8
  • 18
0

You shouldn't directly change state, instead use setState.

import React, { Fragment, Component } from "react";
import MaterialTable from "material-table";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends Component {
  state = {
    items: [],
    chosen: [],
    selected: []
  };

  toggle = id => {
    const selected = this.state.selected;

    if (selected.includes(id)) selected.splice(selected.indexOf(id), 1);
    else selected.push(id);

    this.setState({ selected });
    localStorage.setItem("chosen", JSON.stringify(selected));

    console.log(this.state);
  };

  async componentDidMount() {
    this.setState({
      items: await (await fetch(
        `${process.env["REACT_APP_API"]}/items`
      )).json(),
      selected: JSON.parse(localStorage.getItem("chosen")) || []
    });
  }

  render() {
    return (
      <Fragment>
        <MaterialTable
          columns={[
            {
              title: "myChecbox",
              render: rowData => {
                return (
                  <input
                    className="toggle_checkbox toggle"
                    type="checkbox"
                    checked={this.state.selected.includes(rowData.id)}
                    onChange={this.toggle.bind(this, rowData.id)}
                  />
                );
              },
              cellStyle: {
                width: 20,
                maxWidth: 20,
                padding: 20
              },
              headerStyle: {
                width: 20,
                maxWidth: 20,
                padding: 20
              }
            },
            {
              title: "Logo",
              field: "name",
              render: rowData => {
                return (
                  <a href={rowData.link} key={rowData.id}>
                    <img
                      className="image"
                      src={rowData.logo}
                      alt={rowData.name}
                    />
                  </a>
                );
              }
            },
            {
              title: "Name",
              field: "name",
              render: rowData => {
                return (
                  <a href={rowData.link} key={rowData.id}>
                    <div className="NameContainer">
                      <h5>{rowData.name}</h5>
                      <span>{rowData.type}</span>
                    </div>
                  </a>
                );
              }
            },
            {
              title: "score",
              field: "score",
              cellStyle: data => {
                if (data === "N/A") {
                  return {
                    color: "#aaa"
                  };
                }
              }
            },
            { title: "Size", field: "size" }
          ]}
          data={
            this.state.items.length
              ? this.state.items.map(item => ({
                  id: item.id,
                  logo: item.Logo.url,
                  name: item.Name,
                  type: item.Type.replace(/_/g, " "),
                  score: item.Score,
                  size: item.Size
                }))
              : [{ name: "LOADING" }]
          }
          options={{
            maxBodyHeight: 1000,
            grouping: true,
            selection: true,
            pageSize: 10,
            doubleHorizontalScroll: true
          }}
          onRowClick={(event, rowData) => {
            this.setState({
              selected: [...this.state.selected, rowData.tableData.id]
            });
          }}
          onSelectionChange={data => {
            this.toggle.bind(this, data.id);
          }}
        />
      </Fragment>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Isaac Pak
  • 4,467
  • 3
  • 42
  • 48
0

You calling wrong, when you actived the selection in Options, you must use dataRow like an array. So here is an example of how to used it https://codesandbox.io/s/7zz0v3m91x

Also about autodfill, it isnt available right now in this table, but if you use the table like in remote mode, you can almost have the same effect because it will appear in the table the element that acomplish

I hope I could help Regards

Orestes
  • 637
  • 1
  • 4
  • 19