简体   繁体   中英

How to dynamically create a table in ReactJS?

I want to make my table row dynamic so it can automatically add new data from the MySQL database but I don't know how. Can you help me?

Here is my static data that I wanted to make dynamic.

 const data = {
   rows: [
 {
  Campus_name: 'National Arabella SHS',
  tel_number: ' 123-12-123',
  action: 
  <div className='action-icon-container'>
        <Tooltip title="Edit" trigger="hover">
            <Link to='/admin/campus/edit-campus/:id' state={{bc_edit_type : 1}}><MdEdit className='action-icon edit' /></Link>
        </Tooltip>
    </div> 
},
{
    Campus_name: 'College of Arabella - Main',
    tel_number: ' 123-12-123',
    action: 
    <div className='action-icon-container'>
        <Tooltip title="Edit" trigger="hover">
            <MdEdit className='action-icon edit' />
        </Tooltip>
    </div> 
  },
  {
    Campus_name: 'College of Arabella Extension',
    tel_number: ' 123-12-123',
    action:
    <div className='action-icon-container'>
        <Tooltip title="Edit" trigger="hover">
            <MdEdit className='action-icon edit' />
        </Tooltip>
    </div> 
  },
]

};

Here is the part where I get the data from the database and store it in 'campusValues' variable.

const CampusPage = () => {
  
  const [campusValues, setCampusValues] = useState([]);

  const GetCampusValues = () => {
     Axios.get("http://localhost:5000/campusValues").then((response) => {
       console.log(response);
       setCampusValues(response.data);
  });
 }

useEffect(() => {
   let ignore = false;
   if (!ignore)  
   GetCampusValues();
   return () => { ignore = true; }
},[]);

 return (...);
}

 export default CampusPage

To make a dynamic table just map the table rows:

<table>
  <tr>
    <th>...</th>
    <th>...</th> 
    <th>...</th>
  </tr>

  {
    campusValues.map(value => (
  <tr key={...}>
    <td>{value.id}</td>
    <td>{value.name}</td> 
    <td>...</td>
  </tr>
    ))
  }
</table>

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