Search code examples
reactjsmaterial-table

How to add <Link> react-router to Material-table?


I am using the material-table library is a Datatable based on Material-UI Table.

The datatable has the properties of editable and add a new record in the same table but I don't want to do it in the same table.

I need use a button because I want it to open a material UI menu. However, I don't know how I can add a link or something similar.

I tried it with the following code snippet but it tells me that Link is not defined even though it does matter

import React, { useState, useEffect } from 'react';
import MaterialTable from 'material-table';
import EditIcon from '@material-ui/icons/Edit';
import { IconButton } from '@material-ui/core';
import  axios  from 'axios';
import { Link} from 'react-router-dom';

export default function TableProducts() {

const url='/api/products';

const [product, setProduct]= useState({Products:[]});


 useEffect(()=>{
    const getProduct=async()=>{
            const response =await axios.get(url);
            setProduct(response.data);
    }
    getProduct();
},[]);

  return (

<MaterialTable
      title="Products"
      columns={[
        {title: 'id',field: 'id', type: 'numeric', hidden:'false'},
        { title: 'nameproduct',field: 'nameproduct', },
        { title: 'description', field: 'description' },
        { title: 'price', field: 'price' },
      ]} 
      data={product.Products}
      options={{
        filtering: true,
        sorting: true
      }}
      actions={[
        {
          icon: 'edit',
          tooltip: 'Edit ',
          onClick: () => 
            <Link to={`/product/${data._id}/edit`}>Edit</Link> 

        }
      ]}
      />

    );
  }

I want to get something like this done

                <Link
                    to={`/product/edit/${product.id}`}
                    className="btn btn-success mr-2">Editar
                </Link>

Solution

  • Did you nest it within a Router component like

    <Router>
    <MaterialTable ...>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/users">Users</Link>
            </li>
          </ul>
        </nav>
       </div>
       </MaterialTable>
      </Router>
    

    Added the part about incorporating Material Table. Just try to make the Router the root container.