Using React to create table from data - reactjs

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

Related

MongoDB - How to retrieve only one specific document from a collection

I have created a database called "Cars" and a collection inside it as, "Cars_info". I have inserted 8 documents inside it as follows.
db.Cars_info.insertMany([
{ car_id: "c1", Company: "Toyota", Model: "Aqua", Year: 2020, Price_in_usd: 25000, Category: "High-end", Country: "Japan" },
{ car_id: "c2", Company: "Toyota", Model: "Premio", Year: 2019, Price_in_usd: 35000, Category: "High-end", Country: "Japan" },
{ car_id: "c3", Company: "Audi", Model: "A6", Year: 2020, Price_in_usd: 55000, Category: "High-end", Country: "Germany" },
{ car_id: "c4", Company: "Tata", Model: "Nano", Year: 2015, Price_in_usd: 10000, Category: "Low-end", Country: "India" },
{ car_id: "c5", Company: "Volkswagen", Model: "Taos", Year: 2022, Price_in_usd: 35000, Category: "High-end", Country: "Germany" },
{ car_id: "c6", Company: "Ford", Model: "Figo", Year: 2019, Price_in_usd: 26000, Category: "High-end", Country: "America" },
{ car_id: "c7", Company: "Mahindra", Model: "Thar", Year: 2018, Price_in_usd: 18000, Category: "Low-end", Country: "India" },
{ car_id: "c8", Company: "Honda", Model: "Vezel", Year: 2015, Price_in_usd: 33000, Category: "High-end", Country: "Japan" }
])
Here I want to retrieve only the third document from the collection. But without matching any field value. like,
db.Cars_info.find({"car_id":"c3"}).pretty()
Is there any way to do this?
You need .skip() and .limit().
Take the document by starting index: 2 and with only 1 document, which is the third document.
Update: Thanks and credit to #Wernfried for pointing out, you need .sort() to guarantee to get the nth of the document. For your scenario, you have to sort by car_id.
Sort Consistency
MongoDB does not store documents in a collection in a particular order. When sorting on a field that contains duplicate values, documents containing those values may be returned in any order.
db.Cars_info.find()
.sort({ "car_id": 1 })
.skip(2)
.limit(1)

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 => (...

How to make a clickable header in react table

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>
);
}
}

react-bootstrap-table2-paginator throwing error like Module not found: Can't resolve 'classnames'

I'm getting following error while running my project in which I'm using react-bootstrap-table2-paginator. But I have installed the module, please find the image below...
./node_modules/react-bootstrap-table2-paginator/lib/src/pagination.js
Module not found: Can't resolve 'classnames' in '/home/edu/pagination/node_modules/react-bootstrap-table2-paginator/lib/src'
My app.js file is as follows:
import React, { Component } from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import paginationFactory from 'react-bootstrap-table2-paginator';
const dataMovie = [{ id: 1, title: 'Conan the Barbarian', year: '1982' },
{ id: 2, title: 'Conan the Barbarian', year: '1983' },
{ id: 3, title: 'Conan the Barbarian', year: '1984' },
{ id: 4, title: 'Conan the Barbarian', year: '1985' },
{ id: 5, title: 'Conan the Barbarian', year: '1986' },
{ id: 1, title: 'Conan the Barbarian', year: '1982' },
{ id: 2, title: 'Conan the Barbarian', year: '1983' },
{ id: 3, title: 'Conan the Barbarian', year: '1984' },
{ id: 4, title: 'Conan the Barbarian', year: '1985' },
{ id: 5, title: 'Conan the Barbarian', year: '1986' },
{ id: 1, title: 'Conan the Barbarian', year: '1982' },
{ id: 2, title: 'Conan the Barbarian', year: '1983' },
{ id: 3, title: 'Conan the Barbarian', year: '1984' },
{ id: 4, title: 'Conan the Barbarian', year: '1985' },
{ id: 5, title: 'Conan the Barbarian', year: '1986' },
{ id: 1, title: 'Conan the Barbarian', year: '1982' },
{ id: 2, title: 'Conan the Barbarian', year: '1983' },
{ id: 3, title: 'Conan the Barbarian', year: '1984' },
{ id: 4, title: 'Conan the Barbarian', year: '1985' },
{ id: 5, title: 'Conan the Barbarian', year: '1986' } ];
const columns = [
{
datafield : 'id',
text: 'ID'
},
{
datafield:'title',
name: 'Title',
},
{
datafield: 'Year',
name: 'year',
},
];
class App extends Component {
render() {
return (
<BootstrapTable keyField='id' data={ dataMovie } columns={ columns } pagination={ paginationFactory() } />
)
}
};
export default App;
dependencies in package.json
"react": "^16.13.1",
"react-bootstrap-table2-paginator": "^2.1.2",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
I have installed react-bootstrap-table2-paginator using the flowing command
npm install react-bootstrap-table2-paginator --save
Add
"dependencies": {
"classnames": "^2.2.6"
},
in /react-bootstrap-table2-paginator/package.json inside node_modules.
In /react-bootstrap-table2-paginator/ run: npm update.
see more https://github.com/react-bootstrap-table/react-bootstrap-table2/pull/1491/files

TypeError: _SchoolProduct__WEBPACK_IMPORTED_MODULE_2___default.a.map is not a function

I am new at ReactJs and try to complete a task from the youtube channel.
I created array "products" in "SchoolProduct.js" then using props I passed the value in Product.js.
Now in App.js, I used map function to get data
(Maybe I understand something wrong about props or map function)
Here is SchoolProduct.js:
const products = [
{
id: "1",
name: "pencil",
price: 1,
description: "this is pencil"
},
{
id: "2",
name: "rubber",
price: 10,
description: "this is rubber"
}
]
this is my Product.js
import React from "react"
function Product(props)
{
return
(
<div>
<h2>{props.product.name}</h2>
<p>{props.product.price.toLocaleString("en-US", {style: "currency",
currency: "USD"})}
- {props.product.description}</p>
</div>
)
}
export default Product
and this my App.js
import React, { Component } from 'react';
import Product from "./Product"
import productsData from "./SchoolProduct"
function App(){
const productsComponents = productsData.map(item => <Product product=
{item}/>)
return (
<div>
{productsComponents}
</div>
)
}
export default App;
The Error is:
TypeError: _SchoolProduct__WEBPACK_IMPORTED_MODULE_2___default.a.map is not a function
its shows error in App.js line no 8, which is "const productsComponents"
I know I create a silly mistake, but I am trying to improve it
I have to export my error in default way,
const products = [
{
id: "1",
name: "pencil",
price: 1,
description: "this is pencil"
},
{
id: "2",
name: "rubber",
price: 10,
description: "this is rubber"
}
]
export default products
export default [
{
id: "1",
name: "Pencil",
price: 1,
description: "Perfect for those who can't remember things! 5/5 Highly recommend."
},
{
id: "2",
name: "Housing",
price: 0,
description: "Housing provided for out-of-state students or those who can't commute"
},
{
id: "3",
name: "Computer Rental",
price: 300,
description: "Don't have a computer? No problem!"
},
{
id: "4",
name: "Coffee",
price: 2,
description: "Wake up!"
},
{
id: "5",
name: "Snacks",
price: 0,
description: "Free snacks!"
},
{
id: "6",
name: "Rubber Duckies",
price: 3.50,
description: "To help you solve your hardest coding problems."
},
{
id: "7",
name: "Fidget Spinner",
price: 21.99,
description: "Because we like to pretend we're in high school."
},
{
id: "8",
name: "Sticker Set",
price: 14.99,
description: "To prove to other devs you know a lot."
}
]

Resources