简体   繁体   中英

how to render data intable using reactjs

i am trying to display data in table fornmat. Data is coming from an api. i need to display table once data recived from api. i am using class component . below i have given what is tried.

//below is my jsx

             <div>
                <input onChange={this.handleSearchChange} placeholder="Search" />
                <div>
                    if (!this.state.user.length) return <div>No data</div>
                    <table>
                    <thead>
                        <th>Color</th>
                        <th>Name</th>
                        <th>Age</th>
                    </thead>
                    <tbody> </tbody>
                    </table>
                </div>
             </div>

//below is my function to get data from api

                        handleSearchChange = (e) => {
                            const { value } = e.target;
                            var self = this;
                            axios
                            .post("http://localhost:3000/user", { namr: value })
                            .then(function (res) {
                                this.setState({ user: res.data }); // Error TypeError: Cannot read property 'setState' of undefined
                            })
                            .catch(function (err) {
                                console.log("Error", err);
                            });
                        };

//below is my api output

                    [
                        {color: "green",name: "test",age: "22"},
                        {color: "red",name: "test2",age: "23"}
                    ]

You can iterate over when the data came into HTML elements:

<table>
  <thead>
    <th>Color</th>
    <th>Name</th>
    <th>Age</th>
  </thead>
  <tbody>
    {user.map(userData => (
      // A unique key for each element
      <tr key={userData.name}>
        <td>{userData.name}</td>
        <td>{userData.color}</td>
        <td>{userData.age}</td>
      </tr>
    ))}
  </tbody>
</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