Reputation: 55
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.
Upvotes: 1
Views: 7706
Reputation: 1520
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!
Upvotes: 4