React.js Material-Table pass selected rows to another page

2.2k views Asked by At

How to redirect to another page with passing selected row data as a prop?

I'm using material-table and I want to pass the selected rows data to another page after clicking the "Export" button, so I can use that data to create some kind of report in another page.

I think I should use history.push() method but it's not working in the onClick method. Can someone please give me any hint?

import React from 'react'
import MaterialTable from 'material-table';

class LeadTable extends React.Component{
    constructor(props) {  
      super(props);
      this.state = { 
        leads : [],
      };
    }
  
    componentDidMount() {
      fetch('http://localhost:5000/api/Leads')
      .then(res => res.json())
      .then((data) => {
        // console.log('Data: ', data[0])
        this.setState({
          leads: data[0]
        })
      })
      .catch(console.log);
    }

    redirectToReport = () => {
      const { history } = this.props;
      history.push('report');
    }

    render(){
      return (
        <div style={{ maxWidth: '100%' , align: 'center'}}>
          <MaterialTable
            title="Reporting"
            columns={[
              ...
            ]}
            data = {this.state.leads}       
            options={{
              selection: true,
              filtering: true,
              sorting: true
            }}
            actions = {[{
              position: "toolbarOnSelect",
              
              tooltip: 'Export the selected activities!',
              icon: 'Export',
  
              onClick: (event, rowData) => {
                console.log("Row Data: " , rowData)
                // rowData has all the selected row and I want to redirect to another page with passing those data.
              }
            }]}
          />
        </div>
    )}
}

export default LeadTable
1

There are 1 answers

2
95faf8e76605e973 On BEST ANSWER

This answer mainly addresses OP's code base which is using class components. If you are using function components you can use react-router hooks such as useHistory


Use withRouter HOC to enable LeadTable component access to history so you can push

const LeadTableWithRouter = withRouter(LeadTable);

Pass object to push function to pass row data

redirectToReport = (rowData) => {
  const { history } = this.props;
  history.push({
    pathname: "/report", // re-route to this path
    state: { name: rowData.name, surname: rowData.surname } // your row data
  });
};

In your other component, use this.props.location.state.<data_name> to access the row data you've passed

class AnotherPage extends React.Component {
  render() {
    return (
      <>
        <p>{this.props.location.state.name}</p>
        <p>{this.props.location.state.surname}</p>
        <Link to="/">go back</Link>
      </>
    );
  }
}

Edit practical-field-xoc8y