简体   繁体   中英

Display data json to table in react

I'm going to build a web with react js. I'm very new to react so I have a problem to make CRUD . For the first I want to display some data json to table. I have file .js that named keranjang.js . it contains jsx to display the table. and I have another named barang.js and want to fill it with the method named tampildata() used to hold json data for example {"nama_barang" : "bolu", "harga" : "10000"} . How I write the method? and how do I call the method and data to display that data into the existing table in keranjang.js ? Hope everyone helps me.

I am assuming that you trying to call external file's method in current component. In your barang.js file export your function that holds json data like

export function tampildata() {
    return [{ "firstname": "first", "lastname": "f"}, {"firstname": "second", "lastname": "l"}];
}

or

export default {
  tampildata() {
    return [{ "firstname": "first", "lastname": "f"}, {"firstname": "second", "lastname": "l"}];
  }
};

Then in your keranjang.js file import your tampildata method and call that method in componentDidMount and set state like below

import React from 'react';
import ReactDOM from 'react-dom';
import { tampildata } from 'barang';

class TableComponent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            json: []
        }
    }

    componentDidMount() {
        this.setState((prevState) => {
            return {
                json: tampildata()
            }
        })
    }

    render() {
        return (
            <div>
                <table>
                    <thead>
                        <th>First Name</th>
                        <th>Last Name</th>
                    </thead>
                    <tbody>
                        {this.state.json.map((data, i) => {
                            return (
                                <tr key={i}>
                                    <td>{data.firstname}</td>
                                    <td>{data.lastname}</td>
                                </tr>
                            )
                        })}
                    </tbody>
                </table>
            </div>
        )
    }
}


ReactDOM.render(
  <TableComponent />, 
  document.getElementById("app")
);

Here is the working jsfiddle . Hope this will helps you!

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