I have a React component and I want to test it with React Testing Library. The component has an initial state but I want to override it for my tests and provide a custom initial state so I can test various things. How to I do that in Jest?
function App() {
const initialState = [
{
id: uuidv4(),
date: new Date(),
desc: "initial",
amount: 0,
type: "travel",
},
];
const [expenses, setExpenses] = useState(initialState);
return (
<div className={Styles.app}>
<h1 className="p-4">Expense tracker</h1>
<Container>
<AddExpense setExpenses={setExpenses} expenses={expenses} />
<FilterExpense expenses={expenses} setExpenses={setExpenses} />
<ListExpense setExpenses={setExpenses} expenses={expenses} />
<BreakdownExpense expenses={expenses} />
</Container>
</div>
);
}
I tried the following but it's not working:
test("custom initial state", () => {
const initialState = [
{
id: 1,
date: new Date(),
desc: "test 1",
amount: 0,
type: "10",
},
{
id: 2,
date: new Date(),
desc: "test 2",
amount: 0,
type: "20",
},
{
id: 3,
date: new Date(),
desc: "test 3",
amount: 0,
type: "30",
},
];
const [expenses, setExpenses] = React.useState(initialState);
render(<App expenses={expenses} />);
expect(screen.getByText(/test 1/i)).toBeInTheDocument();
expect(screen.getByText(/test 2/i)).toBeInTheDocument();
});
--- Update
I have a fix for it but I don't like the implementation. I'm putting testing data and logic in the component but I should be keeping them separate.
App comp:
function App({ testApp }) {
const testInitialState = [
{
id: 1,
date: new Date(),
desc: "test 1",
amount: 0,
type: "10",
},
{
id: 2,
date: new Date(),
desc: "test 2",
amount: 0,
type: "20",
},
{
id: 3,
date: new Date(),
desc: "test 3",
amount: 0,
type: "30",
},
];
const initialState = [
{
id: uuidv4(),
date: new Date(),
desc: "initial",
amount: 0,
type: "initial",
},
];
const [expenses, setExpenses] = useState(
testApp ? testInitialState : initialState
);
return (......
test.js:
test(("filter expenses buttons", () => {
render(<App testApp={true} />);
expect(screen.getByText(/test 1/i)).toBeInTheDocument();
expect(screen.getByText(/test 2/i)).toBeInTheDocument();
});
Related
I am trying to filter array as per gender (using checkbox ) but its not working. When i clicked on male checkbox it works but it wont work by clicking on female checkbox button. Here is my App.tsx. Need help to solve this?
import React, { useState } from "react";
const App = () => {
const [students, setStudents] = useState([
{ id: 1, title: "Akita from place1", race: "Akita", gender: 'female' },
{ id: 2, title: "Akita from place2", race: "Akita", gender: 'female' },
{ id: 3, title: "Akita from place3", race: "Akita", gender: 'female' },
{ id: 4, title: "Chihuahua from place4", race: "Chihuahua" , gender: 'male' },
{ id: 5, title: "Cockapoo from place5", race: "Cockapoo" , gender: 'male'},
{ id: 6, title: "Dachshund from place6", race: "Dachshund", gender: 'male' },
{ id: 7, title: "Dutch Shepherd from place7", race: "Dutch Shepherd" , gender: 'female' },
{ id: 8, title: "Bulldog from place8", race: "Bulldog", gender: 'male' },
{ id: 9, title: "Goldador from place9", race: "Goldador", gender: 'female' },
]);
const filterData = (e: any) => {
console.log(e.target.value);
if (e.target.value === "male") {
const filteredData = students.filter((student) => {
return student.gender === "male";
});
setStudents(filteredData);
}
if (e.target.value === "female") {
const filteredData = students.filter((student) => {
return student.gender === "female";
});
setStudents(filteredData);
}
};
return (
<div>
<h3>app</h3>
Male: <input type="checkbox" name='male' value='male' onChange={filterData} />
Female: <input type="checkbox" name='female' value='female' onChange={filterData} />
{students
.map((student: any) => {
return (
<div key={student.id}>
{student.id}-{student.title}-{student.race}-{student.gender}
</div>
);
})}
</div>
);
};
export default App;
const {
useState
} = React;
const App = () => {
const [students, setStudents] = React.useState([{
id: 1,
title: "Akita from place1",
race: "Akita",
gender: 'female'
},
{
id: 2,
title: "Akita from place2",
race: "Akita",
gender: 'female'
},
{
id: 3,
title: "Akita from place3",
race: "Akita",
gender: 'female'
},
{
id: 4,
title: "Chihuahua from place4",
race: "Chihuahua",
gender: 'male'
},
{
id: 5,
title: "Cockapoo from place5",
race: "Cockapoo",
gender: 'male'
},
{
id: 6,
title: "Dachshund from place6",
race: "Dachshund",
gender: 'male'
},
{
id: 7,
title: "Dutch Shepherd from place7",
race: "Dutch Shepherd",
gender: 'female'
},
{
id: 8,
title: "Bulldog from place8",
race: "Bulldog",
gender: 'male'
},
{
id: 9,
title: "Goldador from place9",
race: "Goldador",
gender: 'female'
},
]);
const [filtered, setFiltered] = useState([])
const filterData = (e) => {
const {value, checked} = e.target;
//check if value not in state and checked is true then add value to state
if(!filtered.includes(value) && checked){
setFiltered([...filtered, value])
}else{
setFiltered(filtered.filter(f=>f!==value))
}
};
const filteredStudent = filtered.length > 0 ? students.filter(s => filtered.includes(s.gender)) : students;
return (
<div>
<h3>app</h3>
Male: <input type="checkbox" name='male' value='male' onChange={filterData}/>
Female: <input type="checkbox" name='female' value='female' onChange={filterData}/>
{filteredStudent
.map((student) => {
return (
<div key={student.id}>
{student.id}-{student.title}-{student.race}-{student.gender}
</div>
);
})}
</div>
);
};
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render( <
App / >
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
It does not work because you are filtering all the female out and updating the state, this means that after clicking one button once, the filtered values does not exist in state anymore. To fix this, you could track the filter type in state and derive the filtered students during render.
Note that you could use radio buttons so only one gender can be selected at a time.
import React, {useState} from "react";
const App = () => {
const [students, setStudents] = useState([
{id: 1, title: "Akita from place1", race: "Akita", gender: 'female'},
{id: 2, title: "Akita from place2", race: "Akita", gender: 'female'},
{id: 3, title: "Akita from place3", race: "Akita", gender: 'female'},
{id: 4, title: "Chihuahua from place4", race: "Chihuahua", gender: 'male'},
{id: 5, title: "Cockapoo from place5", race: "Cockapoo", gender: 'male'},
{id: 6, title: "Dachshund from place6", race: "Dachshund", gender: 'male'},
{id: 7, title: "Dutch Shepherd from place7", race: "Dutch Shepherd", gender: 'female'},
{id: 8, title: "Bulldog from place8", race: "Bulldog", gender: 'male'},
{id: 9, title: "Goldador from place9", race: "Goldador", gender: 'female'},
]);
const [filter, setFilter] = useState<null | string>(null)
const filterData = (e) => {
setFilter(e.target.checked ? e.target.value : null)
};
const filteredStudent = filter ? students.filter(s => s.gender === filter) : students;
return (
<div>
<h3>app</h3>
Male: <input type="checkbox" name='male' value='male' onChange={filterData}/>
Female: <input type="checkbox" name='female' value='female' onChange={filterData}/>
{filteredStudent
.map((student) => {
return (
<div key={student.id}>
{student.id}-{student.title}-{student.race}-{student.gender}
</div>
);
})}
</div>
);
};
export default App;
This is shop page.jsx file here i want to show the list of filtered items at the top of the page. Here im using data list for getting all the details. Here i want to show length of filtered products at showing 9 0f 9 products.
import React, { useEffect, useState } from 'react';
import EmptyView from '../components/common/EmptyView';
import FilterPanel from '../components/Home/FilterPanel';
import List from './Home/List';
// import SearchBar from '../../components/Home/SearchBar';
import { dataList } from '../constants';
// import './styles.css';
import '../App.css';
import ButtonAppBar from "./Header";
const Shop = () => {
// const [selectedCategory, setSelectedCategory] = useState(null);
// const [selectedRating, setSelectedRating] = useState(null);
const [selectedPrice, setSelectedPrice] = useState([0, 150]);
const [cuisines, setCuisines] = useState([
{ id: 1, checked: false, label: 'Furniture' },
{ id: 2, checked: false, label: 'Decoration' },
{ id: 3, checked: false, label: 'Bedding' },
{ id: 4, checked: false, label: 'Lighting' },
{ id: 5, checked: false, label: 'Bath&Shower' },
{ id: 6, checked: false, label: 'Curtains' },
{ id: 7, checked: false, label: 'Toys' },
]);
const [brand, setBrand] = useState([
{ id: 1, checked: false, label: 'Poliform' },
{ id: 2, checked: false, label: 'Rochie Bobois' },
{ id: 3, checked: false, label: 'Edra' },
{ id: 4, checked: false, label: 'Kartell' },
]);
const [availability, setAvailability] = useState([
{ id: 1, checked: false, label: 'Onstock' },
{ id: 2, checked: false, label: 'Outofstock' },
]);
const [list, setList] = useState(dataList);
const [resultsFound, setResultsFound] = useState(true);
// const [searchInput, setSearchInput] = useState('');
// const handleSelectCategory = (event, value) =>
// !value ? null : setSelectedCategory(value);
// const handleSelectRating = (event, value) =>
// !value ? null : setSelectedRating(value);
const handleChangeChecked = (id) => {
const cusinesStateList = cuisines;
const changeCheckedCuisines = cusinesStateList.map((item) =>
item.id === id ? { ...item, checked: !item.checked } : item
);
setCuisines(changeCheckedCuisines);
};
const handleChangeCheckeds = (id) => {
const brandStateList = brand;
const changeCheckedsBrand = brandStateList.map((item) =>
item.id === id ? { ...item, checked: !item.checked } : item
);
setBrand(changeCheckedsBrand);
};
const handleChangeCheckedss = (id) => {
const availabilityStateList = availability;
const changeCheckedssAvailability = availabilityStateList.map((item) =>
item.id === id ? { ...item, checked: !item.checked } : item
);
setAvailability(changeCheckedssAvailability);
};
const handleChangePrice = (event, value) => {
setSelectedPrice(value);
};
const applyFilters = () => {
let updatedList = dataList;
// // Rating Filter
// if (selectedRating) {
// updatedList = updatedList.filter(
// (item) => parseInt(item.rating) === parseInt(selectedRating)
// );
// }
// // Category Filter
// if (selectedCategory) {
// updatedList = updatedList.filter(
// (item) => item.category === selectedCategory
// );
// }
// Cuisine Filter
const cuisinesChecked = cuisines
.filter((item) => item.checked)
.map((item) => item.label.toLowerCase());
if (cuisinesChecked.length) {
updatedList = updatedList.filter((item) =>
cuisinesChecked.includes(item.cuisine)
);
}
// brand filter
const brandChecked = brand
.filter((item) => item.checked)
.map((item) => item.label.toLowerCase());
if (brandChecked.length) {
updatedList = updatedList.filter((item) =>
brandChecked.includes(item.brand)
);
}
// availabilty filter
const availabilityChecked = availability
.filter((item) => item.checked)
.map((item) => item.label.toLowerCase());
if (availabilityChecked.length) {
updatedList = updatedList.filter((item) =>
availabilityChecked.includes(item.availability)
);
}
// // Search Filter
// if (searchInput) {
// updatedList = updatedList.filter(
// (item) =>
// item.title.toLowerCase().search(searchInput.toLowerCase().trim()) !==
// -1
// );
// }
// // Price Filter
const minPrice = selectedPrice[0];
const maxPrice = selectedPrice[1];
updatedList = updatedList.filter(
(item) => item.price >= minPrice && item.price <= maxPrice
);
setList(updatedList);
!updatedList.length ? setResultsFound(false) : setResultsFound(true);
};
useEffect(() => {
applyFilters();
}, [cuisines, brand, availability, selectedPrice]);
return (
<div>
<ButtonAppBar />
<div className='home'>
{/* Search Bar */}
{/* <SearchBar
value={searchInput}
changeInput={(e) => setSearchInput(e.target.value)}
/> */}
<br /><br /><br /> <div className='home_panelList-wrap'>
{/* Filter Panel */}
<div className='home_panel-wrap'>
<FilterPanel
// selectedCategory={selectedCategory}
// selectCategory={handleSelectCategory}
// selectedRating={selectedRating}
selectedPrice={selectedPrice}
// selectRating={handleSelectRating}
cuisines={cuisines}
changeChecked={handleChangeChecked}
brand={brand}
changeCheckeds={handleChangeCheckeds}
availability={availability}
changeCheckedss={handleChangeCheckedss}
changePrice={handleChangePrice}
/>
</div>
{/* List & Empty View */}
<div className='home_list-wrap'>
<h6>Showing
<span style={{ color: "#bd744c" }}><b>{dataList.length}</b></span> of
<span style={{ color: "#bd744c" }}><b>9</b></span>
Products</h6>
{resultsFound ? <List list={list} /> : <EmptyView />}
</div>
</div>
</div>
</div>
);
};
export default Shop;
This is constant.js file from here we are getting all our details in shop.jsx file.
export const dataList = [
{
id: 1,
title: 'AwesomeLamp',
cuisine: 'lighting',
price: 40,
image: '/images/AwesomeLamp.png',
brand: 'poliform',
availability: 'onstock',
name: 'AwesomeLamp',
tagName: 'AwesomeLamp'
},
{
id: 2,
title: 'CozySofa',
cuisine: 'furniture',
price: 150,
image: '/images/CozySofa.png',
brand: 'edra',
availability: 'outofstock',
name: 'CozySofa',
tagName: 'CozySofa'
},
{
id: 3,
title: 'AwesomeCandle',
cuisine: 'lighting',
price: 15,
image: '/images/AwesomeCandle.png',
brand: 'kartell',
availability: 'onstock',
name: 'AwesomeCandle',
tagName: 'AwesomeCandle',
},
{
id: 4,
title: 'FancyChair',
cuisine: 'furniture',
price: 70,
image: '/images/FancyChair.png',
brand: 'poliform',
availability: 'outofstock',
name: 'FancyChair',
tagName: 'FancyChair'
},
{
id: 5,
title: 'ChineseTeapot',
cuisine: 'decoration',
price: 50,
image: '/images/ChineseTeapot.png',
brand: 'rochie bobois',
availability: 'onstock',
name: 'ChineseTeapot',
tagName: 'ChineseTeapot'
},
{
id: 6,
title: 'SoftPillow',
cuisine: 'bedding',
price: 30,
image: '/images/SoftPillow.png',
brand: 'edra',
availability: 'onstock',
name: 'SoftPillow',
tagName: 'SoftPillow'
},
{
id: 7,
title: 'WoodenCasket',
cuisine: 'decoration',
price: 20,
image: '/images/WoodenCasket.png',
brand: 'kartell',
availability: 'onstock',
name: 'WoodenCasket',
tagName: 'WoodenCasket'
},
{
id: 8,
title: 'AwesomeArmChair',
cuisine: 'furniture',
price: 90,
image: '/images/AwesomeArmChair.png',
brand: 'poliform',
availability: 'onstock',
name: 'AwesomeArmchair',
tagName: 'AwesomeArmchair'
},
{
id: 9,
title: 'CoolFlower',
cuisine: 'decoration',
price: 20,
image: '/images/CoolFlower.png',
brand: 'none',
availability: 'onstock',
name: 'CoolFlower',
tagName: 'CoolFlower'
},
];
I am fetching data from backend for Drag and Drop
const [productsList, setProductsList] = useState([]);
const loadData=async() =>
{
const response=await fetch("http://localhost:8000/api/getcandidates/");
const data=await response.json();
// console.log(data);
const savedate=data.candidate;
var myObject = JSON.parse(savedate);
setProductsList(myObject);
};
useEffect(() => {
loadData();
},[]);
So I got respond as
const items2FromBackend = [
{ id: 1, content: "First task", title: "JAVA DEVELOPER2", name:"shanu", status: "Inprogress", Skill: "HTML, CSS, JavaScript" , view: "", exp: "4.6Yrs", ctc: " 5LK/A", exctc: " 5LK/A", location: "kakkand", np: "2 Mth" },
{ id: 2, content: "First task", title: "JAVA DEVELOPER", name:"shanu", status: "Inprogress", Skill: "HTML, CSS, JavaScript" , view: "", exp: "4.6Yrs", ctc: " 5LK/A", exctc: " 5LK/A", location: "kakkand", np: "2 Mth"},
{ id: 3, content: "First task", title: "JAVA DEVELOPER2", name:"shanu", status: "Inprogress", Skill: "HTML, CSS, JavaScript" , view: "", exp: "4.6Yrs", ctc: " 5LK/A", exctc: " 5LK/A", location: "kakkand", np: "2 Mth"},
{ id: 4, content: "First task", title: "JAVA DEVELOPER", name:"shanu", status: "Inprogress", Skill: "HTML, CSS, JavaScript" , view: "", exp: "4.6Yrs", ctc: " 5LK/A", exctc: " 5LK/A", location: "kakkand", np: "2 Mth" },
{ id: 5, content: "First task", title: "JAVA DEVELOPER", name:"shanu", status: "Inprogress", Skill: "HTML, CSS, JavaScript" , view: "", exp: "4.6Yrs", ctc: " 5LK/A", exctc: " 5LK/A", location: "kakkand", np: "2 Mth" }
];
and this for drag and drop uuid
const columnsFromBackend = {
[uuid()]: {
name: "Inprogress",
items: productsList
},
[uuid()]: {
name: "Schedule",
items: []
},
[uuid()]: {
name: "Rejection",
items: []
},
[uuid()]: {
name: "Waiting",
items: []
}
};
const [columns, setColumns] = useState(columnsFromBackend);
useState(columnsFromBackend) is not working for back end fetch data productsList.But its working for hardcore data. Any help would be appreciated. Thanks in advance
Since you still need to await for the columnsFromBackend you need to use the setter instead of making it as a "default value". If you call useState(defaultValue). the parameter inside is the defaultValue and it will only be set once.
so in your case what you can do isv put it inside a useState:
const [columns, setColumns] = useState([]);
useState(() => {
setColumns(columnsFromBackend);
}, [columnsFromBackend])
So every time there is a change from columnsFromBackend it will update your state.
I have recently downloaded the react-picky and have used it inside a map function to loop through my dynamic data. In the picky i have set multiselect as true.
How ever on the onchange function am getting only the currently selected value and not the list of values selected for picky.
The issue am facing is in the case of multiselect where the value will be a single object containing the current selected item rather than the list of items selected. Could you please help me with the issue. I have tried every possible solution and it does not seem to work.Any help would be really appreciated as am stuck in the issue for sometime.
const sectorsData = [
{
name: "Technology",
options: [
{
id: "1",
name: "AI & Analytics"
},
{
id: "2",
name: "Robotics"
},
{
id: "3",
name: "IoT"
}
]
},
{
name: "Sector",
options: [
{
id: "1",
name: "Automotive"
},
{
id: "2",
name: "Oil and gas"
},
{
id: "3",
name: "Consumer Products"
}
]
},
{
name: "Accounts",
options: [
{
id: "1",
name: "Alphabet Inc."
},
{
id: "2",
name: "General Motors Company"
},
{
id: "3",
name: "Consumer Products"
},
{
id: "4",
name: "State Street Corporation"
}
]
},
{
name: "Region",
options: [
{
id: "1",
name: "Canada Region"
},
{
id: "2",
name: "Central"
},
{
id: "3",
name: "FSO Americas"
},
{
id: "4",
name: "Latam North"
},
{
id: "5",
name: "Latam South"
}
]
}
];
const App = props => {
const [assetsAddedState, setAssetsAddedState] = React.useState({
selectedItems: []
});
const selectedOption = (name, value) => {
setAssetsAddedState(prev => {
return { ...prev, [name]: value };
});
};
return (
<form className="create-work-form-container" noValidate autoComplete="off">
{sectorsData.map((selectItem, i) => (
<Picky
value={assetsAddedState[selectItem.name]}
onChange={selectedOption.bind(this, selectItem.name)}
options={selectItem.options}
placeholder={selectItem.name}
numberDisplayed={1}
valueKey="id"
labelKey="name"
multiple={true}
includeSelectAll={true}
includeFilter={true}
dropdownHeight={600}
className="multiSelectControl "
name={selectItem.name}
/>
))}
</form>
);
};
value should be returning the multiple values user has selected.
See if this is working for you:
Working example on CodeSandbox:
https://codesandbox.io/s/react-pickyanswerso-yp02j
import React from "react";
import { render } from "react-dom";
import Picky from "react-picky";
import "react-picky/dist/picky.css";
const sector1 = {
name: "Technology",
options: [
{
id: "1",
name: "AI & Analytics"
},
{
id: "2",
name: "Robotics"
},
{
id: "3",
name: "IoT"
}
]
};
const sector2 = {
name: "Sector",
options: [
{
id: "4",
name: "Automotive"
},
{
id: "5",
name: "Oil and gas"
},
{
id: "6",
name: "Consumer Products"
}
]
};
const sector3 = {
name: "Accounts",
options: [
{
id: "7",
name: "Alphabet Inc."
},
{
id: "8",
name: "General Motors Company"
},
{
id: "9",
name: "Consumer Products"
},
{
id: "10",
name: "State Street Corporation"
}
]
};
const sector4 = {
name: "Region",
options: [
{
id: "11",
name: "Canada Region"
},
{
id: "12",
name: "Central"
},
{
id: "13",
name: "FSO Americas"
},
{
id: "14",
name: "Latam North"
},
{
id: "15",
name: "Latam South"
}
]
};
const App = props => {
// const [assetsAddedState, setAssetsAddedState] = React.useState([]);
const [selected1, setSelected1] = React.useState([]);
const [selected2, setSelected2] = React.useState([]);
const [selected3, setSelected3] = React.useState([]);
const [selected4, setSelected4] = React.useState([]);
const selectedOption1 = value => {
console.log("VAlue: " + JSON.stringify(value));
setSelected1(value);
};
const selectedOption2 = value => {
console.log("VAlue: " + JSON.stringify(value));
setSelected2(value);
};
const selectedOption3 = value => {
console.log("VAlue: " + JSON.stringify(value));
setSelected3(value);
};
const selectedOption4 = value => {
console.log("VAlue: " + JSON.stringify(value));
setSelected4(value);
};
return (
<form className="create-work-form-container" noValidate autoComplete="off">
<Picky
value={selected1}
onChange={selectedOption1}
options={sector1.options}
placeholder={sector1.name}
numberDisplayed={1}
valueKey="id"
labelKey="name"
multiple={true}
includeSelectAll={true}
includeFilter={true}
dropdownHeight={600}
className="multiSelectControl "
name={sector1.name}
/>
<Picky
value={selected2}
onChange={selectedOption2}
options={sector2.options}
placeholder={sector2.name}
numberDisplayed={1}
valueKey="id"
labelKey="name"
multiple={true}
includeSelectAll={true}
includeFilter={true}
dropdownHeight={600}
className="multiSelectControl "
name={sector2.name}
/>
<Picky
value={selected3}
onChange={selectedOption3}
options={sector3.options}
placeholder={sector3.name}
numberDisplayed={1}
valueKey="id"
labelKey="name"
multiple={true}
includeSelectAll={true}
includeFilter={true}
dropdownHeight={600}
className="multiSelectControl "
name={sector3.name}
/>
<Picky
value={selected4}
onChange={selectedOption4}
options={sector4.options}
placeholder={sector4.name}
numberDisplayed={1}
valueKey="id"
labelKey="name"
multiple={true}
includeSelectAll={true}
includeFilter={true}
dropdownHeight={600}
className="multiSelectControl "
name={sector4.name}
/>
</form>
);
};
render(<App />, document.getElementById("root"));
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."
}
]