How to make a clickable header in react table - reactjs

Im curious how one goes about making a header clickable while working with tables in react. Ive been digging through posts and forums for some time to no avail.
Here is what I have tried so far:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
manufacturer: "Toyota",
model: "Rav4",
year: 2008,
stock: 3,
price: 8500,
},
{
manufacturer: "Toyota",
model: "Camry",
year: 2009,
stock: 2,
price: 6500,
},
{
manufacturer: "Toyota",
model: "Tacoma",
year: 2016,
stock: 1,
price: 22000,
},
{
manufacturer: "BMW",
model: "i3",
year: 2012,
stock: 5,
price: 12000,
},
{
manufacturer: "Chevy",
model: "Malibu",
year: 2015,
stock: 2,
price: 10000,
},
{
manufacturer: "Honda",
model: "Accord",
year: 2013,
stock: 1,
price: 9000,
},
{
manufacturer: "Hyundai",
model: "Elantra",
year: 2013,
stock: 2,
price: 7000,
},
{
manufacturer: "Chevy",
model: "Cruze",
year: 2012,
stock: 2,
price: 5500,
},
{
manufacturer: "Dodge",
model: "Charger",
year: 2013,
stock: 2,
price: 16000,
},
{
manufacturer: "Ford",
model: "Mustang",
year: 2009,
stock: 1,
price: 8000,
},
],
};
}
render() {
return (
<div>
<Table clickableHeader={onHeaderClick} data={this.state.cars} />
</div>
);
}
}
const onHeaderClick = () => {
return {
onClick: () => {
return <p>hi</p>;
},
};
};
class Table extends React.Component {
constructor(props) {
super(props);
}
render() {
const tableHeads = Object.keys(this.props.data[0]);
return (
<table border="0">
<thead>
<th>Manufacturer</th>
<th>Model</th>
<th {...clickableHeader(column)} >Year</th>
<th>Stock</th>
<th>Price</th>
<th>Option</th>
</thead>
<tbody>
{this.props.data.map((value, key) => (
<tr key={key}>
<td>{value.manufacturer}</td>
<td>{value.model}</td>
<td>{value.year}</td>
<td>{value.stock}</td>
<td>{value.price}</td>
<button>Increment</button>
</tr>
))}
</tbody>
</table>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"))
However, this produces nothing. Perhaps I've implemented it wrong.
When clickable header is taken out, this is what I get
My goal is to make the header labled, Year, clickable. It will sort the data in ascending or descending order based on year.
Here is the post I was using as a reference: How to make a header clickable in react table

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
manufacturer: "Toyota",
model: "Rav4",
year: 2008,
stock: 3,
price: 8500,
},
{
manufacturer: "Toyota",
model: "Camry",
year: 2009,
stock: 2,
price: 6500,
},
{
manufacturer: "Toyota",
model: "Tacoma",
year: 2016,
stock: 1,
price: 22000,
},
{
manufacturer: "BMW",
model: "i3",
year: 2012,
stock: 5,
price: 12000,
},
{
manufacturer: "Chevy",
model: "Malibu",
year: 2015,
stock: 2,
price: 10000,
},
{
manufacturer: "Honda",
model: "Accord",
year: 2013,
stock: 1,
price: 9000,
},
{
manufacturer: "Hyundai",
model: "Elantra",
year: 2013,
stock: 2,
price: 7000,
},
{
manufacturer: "Chevy",
model: "Cruze",
year: 2012,
stock: 2,
price: 5500,
},
{
manufacturer: "Dodge",
model: "Charger",
year: 2013,
stock: 2,
price: 16000,
},
{
manufacturer: "Ford",
model: "Mustang",
year: 2009,
stock: 1,
price: 8000,
},
],
};
}
render() {
return (
<div>
<Table clickableHeader={this.onHeaderClick} data={this.state.cars} />
</div>
);
}
onHeaderClick = (data) => {
return {
onClick: () => {
return <p>hi</p>;
},
};
};
}
class Table extends React.Component {
constructor(props) {
super(props);
}
render() {
const tableHeads = Object.keys(this.props.data[0]);
return (
<table border="0">
<thead>
<th>Manufacturer</th>
<th>Model</th>
<th onClick={() => this.props.onHeaderClick(data)} >Year</th>
<th>Stock</th>
<th>Price</th>
<th>Option</th>
</thead>
<tbody>
{this.props.data.map((value, key) => (
<tr key={key}>
<td>{value.manufacturer}</td>
<td>{value.model}</td>
<td>{value.year}</td>
<td>{value.stock}</td>
<td>{value.price}</td>
<button>Increment</button>
</tr>
))}
</tbody>
</table>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"))
Try like this! :>

Turns out I needed to put all my <th> inside of a <tr> that and using ()=> this helped a lot.
function onHeaderClick(){
return <p> hi</p>;
}
class Table extends React.Component {
constructor(props) {
super(props);
}
render() {
const tableHeads = Object.keys(this.props.data[0]);
return (
<table border="0">
<thead>
<tr>
<th>Manufacturer</th>
<th>Model</th>
<th onClick={()=> this.onHeaderClick}>Year</th>
<th>Stock</th>
<th>Price</th>
<th>Option</th>
</tr>
</thead>
<tbody>
{this.props.data.map((value, key) => (
<tr key={key}>
<td>{value.manufacturer}</td>
<td>{value.model}</td>
<td>{value.year}</td>
<td>{value.stock}</td>
<td>{value.price}</td>
<td>
<button>Increment</button>
</td>
</tr>
))}
</tbody>
</table>
);
}
}

Related

How to use setState in functional component React?

I was using classes. I changed it to functional components. But in handleLike method. I cant seem to understand how to use setState. Anyhelp with how to do it? In my current useState im getting array of objects. When I click on like button it displays an error that movies.map is not a function. Thankyou
movies.jsx
import React, { Component, useState } from "react";
import { getMovies } from "../services/fakeMovieService";
import Like from "./like";
function Movies() {
const initialMovies = getMovies();
const [movies, setMovies] = useState(initialMovies);
const handleDelete = (movie) => {
setMovies((movies) => movies.filter((m) => m._id !== movie._id));
};
const handleLike = (movie) => {
const movies = [...movies]
const index = movies.indexOf(movie)
movies[index] = { ...movie[index]}
movies[index].liked = !movies[index].liked
setMovies({ movies })
};
const { length: count } = movies;
if (count === 0) return <p>There are no movies in database</p>;
return (
<React.Fragment>
<p> Showing {count} movies in the database</p>
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Genre</th>
<th>Stock</th>
<th>Rate</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{movies.map((movie) => (
<tr key={movie._id}>
<td>{movie.title}</td>
<td>{movie.genre.name}</td>
<td>{movie.numberInStock}</td>
<td>{movie.dailyRentalRate}</td>
<td>
<Like liked={movie.liked} onClick={()=> handleLike(movie)} />
</td>
<td>
<button
onClick={() => handleDelete(movie)}
className="btn btn-danger btn-sm"
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</React.Fragment>
);
}
Like.jsx
class Like extends React.Component {
render() {
let classes = "fa fa-heart";
if (!this.props.liked) classes+= "-o"
return (
<i
className={classes}
aria-hidden="true"
onClick={this.props.onClick}
style={{cursor:"pointer"}}
></i>
);
}
}
JSON FILE
const movies = [
{
_id: "5b21ca3eeb7f6fbccd471815",
title: "Terminator",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 6,
dailyRentalRate: 2.5,
publishDate: "2018-01-03T19:04:28.809Z",
liked: true,
},
{
_id: "5b21ca3eeb7f6fbccd471816",
title: "Die Hard",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 5,
dailyRentalRate: 2.5
},
{
_id: "5b21ca3eeb7f6fbccd471817",
title: "Get Out",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 8,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd471819",
title: "Trip to Italy",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181a",
title: "Airplane",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181b",
title: "Wedding Crashers",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181e",
title: "Gone Girl",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 7,
dailyRentalRate: 4.5
},
{
_id: "5b21ca3eeb7f6fbccd47181f",
title: "The Sixth Sense",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 4,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd471821",
title: "The Avengers",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 7,
dailyRentalRate: 3.5
}
];
export function getMovies() {
return movies;
}
You have a few redundant object/array assignment in your code
So, update your handleLike like so:
const handleLike = (movie) => {
const _movies = [...movies];
const index = movies.indexOf(movie);
_movies[index].liked = !movies[index].liked;
setMovies(_movies);
};
Working Example:

How to set local JSON data into functional components in React?

I'm new to react. I got stucked here. I'm not sure how to pass json data that is getting returned as function to useState.I used classes and everything worked perfectly fine. Now i'm trying to convert that code into functional components. When I delete an item it displays an error. movie.filter is not a function.
index.js
import React, { Component,useState } from 'react'
import {getMovies} from "../services/fakeMovieService"
function Movies() {
const movies = getMovies()
const [movie, setMovie] = useState(movies);
const handleDelete = (movie) => {
const newM= movie.filter(m => m._id != movie._id)
setMovie({newM})
}
return (
<React.Fragment>
<table className="table">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
{movie.map(movie =>(
<tr key={movie._id}>
<td>{movie.title}</td>
<td>{movie.genre.name}</td>
<td>{movie.numberInStock}</td>
<td>{movie.dailyRentalRate}</td>
<td><button onClick={()=>handleDelete(movie)} className="btn btn-danger btn-sm">Delete</button></td>
</tr>
))
}
</tbody>
</table>
</React.Fragment>
);
}
export default Movies;
JSON
import * as genresAPI from "./fakeGenreService";
const movies = [
{
_id: "5b21ca3eeb7f6fbccd471815",
title: "Terminator",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 6,
dailyRentalRate: 2.5,
publishDate: "2018-01-03T19:04:28.809Z"
},
{
_id: "5b21ca3eeb7f6fbccd471816",
title: "Die Hard",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 5,
dailyRentalRate: 2.5
},
{
_id: "5b21ca3eeb7f6fbccd471817",
title: "Get Out",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 8,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd471819",
title: "Trip to Italy",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181a",
title: "Airplane",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181b",
title: "Wedding Crashers",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181e",
title: "Gone Girl",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 7,
dailyRentalRate: 4.5
},
{
_id: "5b21ca3eeb7f6fbccd47181f",
title: "The Sixth Sense",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 4,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd471821",
title: "The Avengers",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 7,
dailyRentalRate: 3.5
}
];
export function getMovies() {
return movies;
}
setMovie({newM})
should be
setMovie(newM)
because your state is an array. The argument movie and state movie have the same name so you're trying to use Array.prototype.filter on an object.
Rename the restructured array values of useState to movies and setMovies:
const initialMovies = getMovies()
const [movies, setMovies] = useState(initialMovies);
Use functional state update as the new state depends on the old state:
const handleDelete = (movie) => {
setMovies(previousMovies => previousMovies.filter(m => m._id !== movie._id))
}
and use movies to render
{movies.map(movie => (...

Using React to create table from data

as the question suggests I am brand new to react and am trying to create a table to display some data.
Here's what I have so far
const { Component } = React;
const { render } = ReactDOM;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
"manufacturer": "Toyota",
"model": "Rav4",
"year": 2008,
"stock": 3,
"price": 8500
},
{
"manufacturer": "Toyota",
"model": "Camry",
"year": 2009,
"stock": 2,
"price": 6500
},
{
"manufacturer": "Toyota",
"model": "Tacoma",
"year": 2016,
"stock": 1,
"price": 22000
},
{
"manufacturer": "BMW",
"model": "i3",
"year": 2012,
"stock": 5,
"price": 12000
},
{
"manufacturer": "Chevy",
"model": "Malibu",
"year": 2015,
"stock": 2,
"price": 10000
},
{
"manufacturer": "Honda",
"model": "Accord",
"year": 2013,
"stock": 1,
"price": 9000
},
{
"manufacturer": "Hyundai",
"model": "Elantra",
"year": 2013,
"stock": 2,
"price": 7000
},
{
"manufacturer": "Chevy",
"model": "Cruze",
"year": 2012,
"stock": 2,
"price": 5500
},
{
"manufacturer": "Dodge",
"model": "Charger",
"year": 2013,
"stock": 2,
"price": 16000
},
{
"manufacturer": "Ford",
"model": "Mustang",
"year": 2009,
"stock": 1,
"price": 8000
},]
};
}
render() {
const columns = [{
Header: 'Manufacturer',
accessor: 'manufacturer'
},{
Header: 'Model',
accessor: 'model'
},{
Header: 'Year',
accessor: 'year'
},{
Header: 'Stock',
accessor: 'stock'
},{
Header: 'Price',
accessor: 'price'
},{
Header: 'Option',
accessor: 'option'
}]
return (
<div>
<Table
data = {this.state.cars}
colums = {columns}
/>
</div>
);
};
}
ReactDOM.render(<App />, document.getElementById("app"))
Im getting errors that the table is not defined but when I try to define it, that throws me errors as well. The table doesn't need to be fancy, the simpler the better in fact.
I was thinking of doing something like what was done in this post: https://codereview.stackexchange.com/questions/212250/generating-a-table-based-on-an-array-of-objects.
Any suggestions?
UPDATE
After the very helpful comment from Crispen Gari, I made some tweaks and came up with this
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
manufacturer: "Toyota",
model: "Rav4",
year: 2008,
stock: 3,
price: 8500,
},
{
manufacturer: "Toyota",
model: "Camry",
year: 2009,
stock: 2,
price: 6500,
},
{
manufacturer: "Toyota",
model: "Tacoma",
year: 2016,
stock: 1,
price: 22000,
},
{
manufacturer: "BMW",
model: "i3",
year: 2012,
stock: 5,
price: 12000,
},
{
manufacturer: "Chevy",
model: "Malibu",
year: 2015,
stock: 2,
price: 10000,
},
{
manufacturer: "Honda",
model: "Accord",
year: 2013,
stock: 1,
price: 9000,
},
{
manufacturer: "Hyundai",
model: "Elantra",
year: 2013,
stock: 2,
price: 7000,
},
{
manufacturer: "Chevy",
model: "Cruze",
year: 2012,
stock: 2,
price: 5500,
},
{
manufacturer: "Dodge",
model: "Charger",
year: 2013,
stock: 2,
price: 16000,
},
{
manufacturer: "Ford",
model: "Mustang",
year: 2009,
stock: 1,
price: 8000,
},
],
};
}
render() {
return (
<div>
<Table data={this.state.cars} />
</div>
);
}
}
class Table extends React.Component {
constructor(props) {
super(props);
}
render() {
const tableHeads = Object.keys(this.props.data[0]);
return (
<table border="1">
<thead>
{tableHeads.map((tableHead, i) => (
<th key={i}>{tableHead}</th>
))}
</thead>
<tbody>
{this.props.data.map((value, key) => (
<tr key={key}>
<td>{value.manufacturer}</td>
<td>{value.model}</td>
<td>{value.year}</td>
<td>{value.stock}</td>
<td>{value.price}</td>
</tr>
))}
</tbody>
</table>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"))
This post can be considered closed
Hey, Try this code if you face any problems of understanding, let me know. I recommend you to copy and paste this code if it works go through it and try to understand. The most important thing is to understand JavaScript higher order function map
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
manufacturer: "Toyota",
model: "Rav4",
year: 2008,
stock: 3,
price: 8500,
},
{
manufacturer: "Toyota",
model: "Camry",
year: 2009,
stock: 2,
price: 6500,
},
{
manufacturer: "Toyota",
model: "Tacoma",
year: 2016,
stock: 1,
price: 22000,
},
{
manufacturer: "BMW",
model: "i3",
year: 2012,
stock: 5,
price: 12000,
},
{
manufacturer: "Chevy",
model: "Malibu",
year: 2015,
stock: 2,
price: 10000,
},
{
manufacturer: "Honda",
model: "Accord",
year: 2013,
stock: 1,
price: 9000,
},
{
manufacturer: "Hyundai",
model: "Elantra",
year: 2013,
stock: 2,
price: 7000,
},
{
manufacturer: "Chevy",
model: "Cruze",
year: 2012,
stock: 2,
price: 5500,
},
{
manufacturer: "Dodge",
model: "Charger",
year: 2013,
stock: 2,
price: 16000,
},
{
manufacturer: "Ford",
model: "Mustang",
year: 2009,
stock: 1,
price: 8000,
},
],
};
}
render() {
return (
<div>
<Table data={this.state.cars} />
</div>
);
}
}
class Table extends React.Component {
constructor(props) {
super(props);
}
render() {
const tableHeads = Object.keys(this.props?.data[0]);
return (
<table border="1">
<thead>
{tableHeads.map((tableHead, i) => (
<th key={i}>{tableHead}</th>
))}
</thead>
<tbody>
{this.props?.data?.map((value, key) => (
<tr key={key}>
<td>{value?.manufacturer}</td>
<td>{value?.model}</td>
<td>{value?.year}</td>
<td>{value?.stock}</td>
<td>{value?.price}</td>
</tr>
))}
</tbody>
</table>
);
}
}
export default App;
I Hope this will help you, Good Luck

React.js Table Component

I am creating a pizza app with React.js and would like to display pizza options in a table. I would like to develop my table using like this table, rather than the way i am doing it in choices.js.
Choices.js
return (
<div className="page-wrap">
<table>
<thead>
<tr>
<th>Pizza Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td key={index}>
<a href onClick={this.handleChoice.bind(this, pizza)}>
{pizza.name}</a></td>
</tr>
<tr>
<td>${pizza.price}</td>
</tr>
</tbody>
</table>
</div>
)
});
Options.js
var pizzas = [
{
name: 'Cheese Pizza',
cheese: 'Mozzarella',
toppings: [],
price: 5
},
{
name: 'Papas Special',
cheese: 'Parmesan',
toppings: ['Spinach', 'Lobster', 'Hot Oil'],
price: 50
},
{
name: 'Wild West',
cheese: 'Spicy Mozzarella',
toppings: ['Red Onions', 'Texas Chilli', 'Grilled Chicken'],
price: 25
},
{
name: 'California Pizza',
cheese: 'Mozzarella',
toppings: ['Spinach', 'Guacamole', 'Cherry Tomato'],
price: 25
},
{
name: 'Buffalo Chicken Pizza',
cheese: 'Spicy Blue Cheese',
toppings: ['Red Onions', 'Texas Chilli'],
price: 25
},
{
name: 'Jerk Chicken Pizza',
cheese: 'Mozzarella',
toppings: ['Red Onions', 'Jerk Sauce'],
price: 25
},
{
name: 'Salad Pizza',
cheese: 'Mozzarella',
toppings: ['Red Onions', 'Lettuce', 'Tomato'],
price: 25
}
];
Are you tring to do this? http://jsfiddle.net/dahdx6eu/337/
var cols = [
{ key: 'Name', label: 'Name' },
{ key: 'Cheese', label: 'Cheese' },
{ key: 'Toppings', label: 'Toppings' },
{ key: 'Price', label: 'Price' },
];
var data = [
{
id: 1,
name: 'Cheese Pizza',
cheese: 'Mozzarella',
toppings: [],
price: 5
},
{
id: 2,
name: 'Papas Special',
cheese: 'Parmesan',
toppings: ['Spinach', 'Lobster', 'Hot Oil'],
price: 50
},
{
id: 3,
name: 'Wild West',
cheese: 'Spicy Mozzarella',
toppings: ['Red Onions', 'Texas Chilli', 'Grilled Chicken'],
price: 25
},
{
id: 4,
name: 'California Pizza',
cheese: 'Mozzarella',
toppings: ['Spinach', 'Guacamole', 'Cherry Tomato'],
price: 25
},
{
id: 5,
name: 'Buffalo Chicken Pizza',
cheese: 'Spicy Blue Cheese',
toppings: ['Red Onions', 'Texas Chilli'],
price: 25
},
{
id: 6,
name: 'Jerk Chicken Pizza',
cheese: 'Mozzarella',
toppings: ['Red Onions', 'Jerk Sauce'],
price: 25
},
{
id: 7,
name: 'Salad Pizza',
cheese: 'Mozzarella',
toppings: ['Red Onions', 'Lettuce', 'Tomato'],
price: 25
}
]
var Table = React.createClass({
render: function() {
var headerComponents = this.generateHeaders(),
rowComponents = this.generateRows();
return (
<table>
<thead> {headerComponents} </thead>
<tbody> {rowComponents} </tbody>
</table>
);
},
generateHeaders: function() {
var cols = this.props.cols; // [{key, label}]
// generate our header (th) cell components
return cols.map(function(colData) {
return <th key={colData.key}> {colData.label} </th>;
});
},
generateRows: function() {
var cols = this.props.cols, // [{key, label}]
data = this.props.data;
return data.map(function(item) {
// handle the column data within each row
console.log(item)
return (<tr key={item.id}><td>{item.name}</td><td>{item.cheese}</td><td>{item.toppings} </td><td>{item.price}</td></tr>);
});
}
});

Two sets of data in one component

I'm passing data to a component with no issue - however, I'd now like to re-use that component with a different data set:
import React from 'react';
const people = [{
id: 1,
name: "John",
age: 32,
hobby: "jogging",
},{
id: 2,
name: "John",
age: 32,
hobby: "jogging",
}];
const cars = [{
id: 1,
manufacturer: "Ford",
model: "Focus",
year: "2014",
},{
id: 2,
manufacturer: "Honda",
model: "Civic",
year: "2012",
}];
export default function ListGroup(props) {
return (
<div>
{props.people.map((person) =>
<li key={person.id}>
<p>Name: {person.name}</p>
<p>Hobby: {person.hobby}</p>
</li>
)}
</div>
);
}
The above code works perfectly for the people fixture, but to use the same component I'm not sure what the simplest path might be. Any guidance welcome.
Iterate over the ids using Object.keys(component).map(function(attributes){}. I have presented it like a component you can use it like a function as well. I hope you can convert it to how you want to use it.
class ListGroup extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
{this.props.value.map((component) => {
return (
<li key={component.id}>
{Object.keys(component).map(function(attributes) {
return (
<p>{attributes} : {component[attributes]}</p>
)
}, this)}
</li>
)
})}
</div>
);
}
}
class Hello extends React.Component {
constructor() {
super();
}
render() {
const people = [{
id: 1,
name: "John",
age: 32,
hobby: "jogging",
},{
id: 2,
name: "John",
age: 32,
hobby: "jogging",
}];
const cars = [{
id: 1,
manufacturer: "Ford",
model: "Focus",
year: "2014",
},{
id: 2,
manufacturer: "Honda",
model: "Civic",
year: "2012",
}];
return (
<div>
<ListGroup value={people} />
<ListGroup value={cars} />
</div>
)
}
}
ReactDOM.render(<Hello /> ,document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>

Resources