简体   繁体   中英

Reactjs: How to make all row checkbox checked true when material table is loaded and deselect when clicked and vice versa?

I am using react material table in my project and i want to make select all by default checked when page is loaded .How to achieve that?? also when i deselect any checkbox, it should get deselected. I tried using

selectionProps: rowData => ({
    checked: true
}),

But it set checked to all checkbox and cannot be deselect.

function BasicSelection() {
  return (
    <MaterialTable
      title="Basic Selection Preview"
      columns={[
        { title: 'Name', field: 'name' },
        { title: 'Surname', field: 'surname' },
        { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
        {
          title: 'Birth Place',
          field: 'birthCity',
          lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
        },
      ]}
      data={[
        { name: 'a', surname: 'b', birthYear: c, birthCity: d },
        { name: 'e', surname: 'f', birthYear: g, birthCity: h },
      ]}        
      options={{
        selection: true
      }}
    />
  )
}

You need to add tableData: { checked: true } for each row data.

function BasicSelection() {
  return (
    <MaterialTable
      title="Basic Selection Preview"
      columns={[
        { title: 'Name', field: 'name' },
        { title: 'Surname', field: 'surname' },
        { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
        {
          title: 'Birth Place',
          field: 'birthCity',
          lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
        },
      ]}
      data={[
        {
            tableData: { checked: true },
            name: 'Mehmet',
            surname: 'Baran',
            birthYear: 1987,
            birthCity: 63 },
        {
           tableData: { checked: true },
           checked: true,
           name: 'Zerya Betül',
           surname: 'Baran', 
           birthYear: 2017, 
           birthCity: 34 },
      ]}      
      options={{
        selection: true
      }}
    />
  )
}

This works exactly the way you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM