0
votes

I'm new to javaScript and ReactJS so this might be an obvious question but i can't figure it out. Im trying to display my array using useState in a table, as of now i can only display the header.

Also if anyone know how to make this table dynamic i.e adding rows automatically after useState has been updated

import React, { useState, useEffect, Component } from 'react'; import Axios from 'axios'

function Table() {

useEffect(() => {
    Axios.get("http://localhost:3001/api/get/carmodels").then((response) => {
      setCarModelList(response.data)
    })
  }, [])

  const [carModelList, setCarModelList] = useState([])

  const renderTableData = () => {
    return carModelList.map((val) => {
        <tr>
            <td>{val.brand}</td>
            <td>{val.model}</td>
            <td>{val.price}</td>
        </tr>
    

  })
}
return (
    <table id='table'>
    <thead>
        <tr>
          <th>Brand</th>
          <th>Model</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
          {renderTableData()}
      </tbody>
      </table>
    );
  

}

export default Table

1
You can create a JSON data structure store the values there. Then you can map the values using jsx (FOR loops) and on every update of the JSON data. It will all be updated.SARAN SURYA

1 Answers

0
votes

your problem is in renderTableData function it's not returning jsx here's the soulution:

const renderTableData = () => {
    return carModelList.map((val) => (
        <tr>
            <td>{val.brand}</td>
            <td>{val.model}</td>
            <td>{val.price}</td>
        </tr>))
}