React Province Disctrict selector - reactjs

I want to list the districts of the province selected from the province option. I am pulling from local json file.
How can I solve this problem?
<div className="flex items-center px-2">
<label for="cars">İl Seçiniz:</label>
<select onChange={(e) => handleProvince(e)}>
<option key={0} value={0}>
Lütfen bir İl seçiniz
</option>
{Provinces.map((province) => (
<option key={province.plaka} value={province.il}>
{province.il}
</option>
))}
</select>
</div>
<div className="flex items-center px-2">
<label for="cars">İlçe Seçiniz:</label>
<select>
{Provinces.map((item) => (
<option key={item.plaka} value={item.ilceleri}>
{item.il === "İstanbul" ? item.ilceleri : null}
</option>
))}
</select>
</div>
dropdown screenshot
json file

You can achieve this by correctly mapping the districts to the option field as seen in the following CodeSandbox: https://codesandbox.io/s/distracted-rain-s4tnxb?file=/src/App.js
const DATA = [
{
province: "Province A",
districts: ["PA district1", "PA district2"]
},
{
province: "Province B",
districts: ["PB district1", "PB district2"]
}
];
export default function App() {
const [province, setProvince] = useState();
const [district, setDistrict] = useState();
const selectProvince = (e) => {
const selectedProvince = DATA.find(
(entry) => entry.province === e.target.value
);
setDistrict(undefined);
setProvince(selectedProvince);
};
const selectDistrict = (e) => {
setDistrict(e.target.value);
};
return (
<div className="App">
<select onChange={selectProvince}>
{DATA.map((entry, index) => {
return (
<option key={index} value={entry.province}>
{entry.province}
</option>
);
})}
</select>
<br></br>
{!!province && (
<select onChange={selectDistrict}>
{province.districts.map((district, index) => {
return (
<option value={district} key={index}>
{district}
</option>
);
})}
</select>
)}
{!!province && (
<p>
Selected province {province.province}
<br></br>
</p>
)}
{!!district && (
<p>
Selected district {district}
<br></br>
</p>
)}
</div>
);
}

Related

how do i get specific data from the state on a button click in react

Here i have 3 products each have it's own addtocart button and it's option like color, size, quantity. so when i click addtocart button after selecting the options it updating the state and giving me exactly i wanted. The problem is when i selelct any product options and then i click on another product addtocart button it shows the selceted option. not the product options of the addtocart button i clicked
for example: i select the 1st product and choose it's options and i did'nt click on the 1st product addtocart button either i clicked 2nd product button but it returns 1st product selected options it should return 2nd product options.
i need to implement which ever the product button i clicks it should only return that product selected options only.it should'nt return any other product selected options.
how do i make this happen. Help me out.
function Card() {
const [items, setItems] = useState({});
const handleChageCategory = (key, event) => {
setItems((oldState) => ({ ...oldState, [key]: event.target.value }));
};
const submitHandler = () => {
console.log(items);
setItems({});
};
return (
<div className="main-container">
<div className="container">
<div className="image-container">
<img
src="https://images.pexels.com/photos/9558601/pexels-photo-9558601.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt=""
/>
</div>
<h2> T-Shirt </h2>
</div>
<div className="form-conatiner">
<div className="selectors">
<p>Solid Round Neck T-shirt</p>
<select
id="color"
name="color"
required
onChange={(event) => handleChageCategory("color", event)}
>
<option>Color</option>
<option value="black">Black</option>
<option value="green">Green</option>
<option value="orange">Orange</option>
</select>
<select
name="quantity"
required
onChange={(event) => handleChageCategory("quantity", event)}
>
<option>Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select
name="size"
required
onChange={(event) => handleChageCategory("size", event)}
>
<option>Size</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="small">Small</option>
</select>
<div>
<button onClick={submitHandler}>Add to Cart</button>
</div>
</div>
</div>
{/* second product */}
<div className="container">
<div className="image-container">
<img
src="https://images.pexels.com/photos/440320/pexels-photo-440320.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt=""
/>
</div>
<h2> i-Watch </h2>
</div>
<div className="form-conatiner">
<div className="selectors">
<p>Dizo watch with amlod </p>
<select
id="2"
name="color"
required
onChange={(event) => handleChageCategory("brand", event)}
>
<option>Brand</option>
<option value="Apple">Apple</option>
<option value="Samsung">Samsung</option>
<option value="Pixel">Pixel</option>
</select>
<select
name="qantity"
required
onChange={(event) => handleChageCategory("qantity", event)}
>
<option>Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select
name="type"
required
onChange={(event) => handleChageCategory("type", event)}
>
<option>type</option>
<option value="29mm">29mm</option>
<option value="34mm">34mm</option>
<option value="42mm">42mm</option>
</select>
<div>
<button onClick={submitHandler}>Add to Cart</button>
</div>
</div>
</div>
{/* third product */}
<div className="container">
<div className="image-container">
<img
src="https://images.pexels.com/photos/1661471/pexels-photo-1661471.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt=""
/>
</div>
<h2> Hoodie </h2>
</div>
<div className="form-conatiner">
<div className="selectors">
<p>Adidas hoodie with zip </p>
<select
id="2"
name="color"
required
onChange={(event) => handleChageCategory("color", event)}
>
<option>Color</option>
<option value="Gray">gray</option>
<option value="White">white</option>
<option value="Cyan">cyan</option>
</select>
<select
name="qantity"
required
onChange={(event) => handleChageCategory("qantity", event)}
>
<option>Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select
name="size"
required
onChange={(event) => handleChageCategory("size", event)}
>
<option>type</option>
<option value="39(S)">39(S)</option>
<option value="42(M)">42(M)</option>
<option value="46(L)">46(L)</option>
</select>
<div>
<button onClick={submitHandler}>Add to Cart</button>
</div>
</div>
</div>
</div>
);
}
export default Card;
const [items, setItems] = useState([]);
The handleChangeCategory Logic
const handleChageCategory = (key,product, event) => {
const isExist = items.find((item)=>item.id===product.id)
let updatedItem
if(isExist){
updatedItem = {...isExist, [key]: event.target.value}
setItems((oldState)=>(oldState.map(item=>item.id===updatedItem.id ? updatedItem: item)))
}else{
updatedItem = { ...product, [key]: event.target.value };
setItems((oldState)=>([...oldState, updatedItem]))
}
};
Submit handler logic:
const submitHandler = (product) => {
const isExist = items.find(item=>item.id===product.id)
const newCartItem = isExist? isExist: product
console.log(newCartItem);
setItems((oldState)=>(oldState.filter(item=>item.id!==newCartItem.id)))
}
I know this is an expensive operation and it might hamper user experience but you wanted to do it this way. To handle add to cart, I think the good way is to open a modal or new page after clicking Add To Cart button that also solves your problem because in this way the user is not able to update one product value and click another product button.
A more efficient way to implement a product list is to use a product component for each item which accepts the product data through props. There you will implement all the logic related to the product and check the selected fields and so on.
Full code here.
So here I created Product, which has a selectedValues state that contains the values of all the selectors as an object, and also an handleAddToCart function that sends this product to the parent component function and add the product to the cart there.
Product.js:
const Product = (props) => {
const [selectedValues, setSelectedValues] = useState({});
const { name, description, img, selectors } = props;
//(`selectors` is an array of objects. Each object is a selector with an id field and an array of the `options`).
const handleChangeCategory = (e) => {
setSelectedValues((prevState) => {
return { ...prevState, [e.target.name]: e.target.value };
});
};
const handleAddToCart = () => {
props.addToCart({ name, description, img, selectedValues });//calling the function from the props.
};
return (
<div className="product">
<div className="image-container">
<img width="150px" src={img} alt="" />
</div>
<h2> {name}</h2>
<div className="form-conatiner">
<p>{description}</p>
<div className="selectors">
{selectors.map((s) => {
return (
<select
id={s.id}
name={s.id}
required
onChange={handleChangeCategory}
>
{s.options.map((opt) => (
<option value={opt}>{opt}</option>
))}
</select>
);
})}
</div>
<button onClick={handleAddToCart}>Add to Cart</button>
</div>
</div>
);
};
export default Product;
And this is the parent component, where you have the cart and the addToCartHandler function. And in the JSX you simply create a product by calling the Product component and passing the data and the selectors you want to have for this product.
App.js (parent component):
export default function App() {
//Some dummy cart.
const DUMMY_CART = [];
//Function that adds a product to the DUMMY_CART
const addToCartHandler = (product) => {
//Do some logic with the cart of course. I'm just pushing it here to show you the result.
DUMMY_CART.push(product);
console.log('Added product:', product);
console.log('Cart:', DUMMY_CART);
};
return (
<div>
{/* Product 1 */}
<Product
img="https://images.pexels.com/photos/9558601/pexels-photo-9558601.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
name="T-Shirt"
description="Solid round neck T-Shirt"
selectors={[
{ id: 'color', options: ['Color', 'blue', 'grin', 'yellow'] },
{ id: 'quantity', options: ['Quantity', 1, 2, 3] },
{ id: 'size', options: ['Size', 'medium', 'large', 'small'] },
]}
addToCart={(product) => addToCartHandler(product)}
/>
</div>
);
}
Hope this helps. Please check the full code to see how it works.

stacked dynamic inputs - reactjs

I have an input and a select starting when placing any value in the case of the input, it begins to generate dynamic statements and in the case of the input, dynamic inputs are generated but in decrement, everything works fine, I only need that the dynamic inputs that begin to appear are show one by one and not all piled up as I show in the picture.
problem image
how do i want it to be
import React, { useState } from "react";
//input dynamic
import Row from "./Row2";
let initialState = {
first: null,
arraySelect: []
};
function Pruebas(props) {
/*input dynamic */
const [rows, setRows] = useState([]);
const [initialeRow, setInitialRow] = useState({ nombre: "" });
const handleOnChange = (index, value) => {
const copy = rows.map((e, i) => {
if (i === index) {
e.nombre = value;
}
return e;
});
setRows([...copy]);
};
const handleOnAdd = () => {
if (initialeRow.nombre >= 1) {
setInitialRow({ nombre: initialeRow.nombre - 1 });
setRows([...rows, initialeRow]);
}
};
/////////////////////////////////////////////////////
const [input_multi, setInput_multi] = useState();
const [arraySelect, setarraySelect] = useState(initialState.arraySelect);
const [numberIni, setnumberIni] = useState(initialState.first);
const getArray = (value) => {
let arr = [];
{
let reco = Math.round(numberIni - parseInt(value));
console.log(reco);
if (parseInt(value) == numberIni) {
return false;
}
Array(reco)
.fill(1)
.map((value2, key) => {
arr.push(parseInt(value) + parseInt(key + 1));
});
}
return arr;
};
const setSelect = (value) => {
let isArray = getArray(value);
if (isArray) {
setarraySelect([...arraySelect, isArray]);
}
//input dynamyc
if (initialeRow.nombre >= 1) {
setInitialRow({ nombre: initialeRow.nombre - 1 });
setRows([...rows, initialeRow]);
}
};
//input dynamic
const handleInput_division = (event) => {
setInitialRow({ nombre: event.target.value });
};
const handleSubmit = (event) => {
event.preventDefault();
setnumberIni(event.target.numberIni.value);
};
const resetForm = () => {
setnumberIni(null);
setarraySelect([]);
};
return (
<div>
<form onSubmit={handleSubmit}>
<div class="row">
<label>PHASES</label>
<div class="col-sm-6">
<h6>enter a number</h6>
<div class="input-group ">
<input
type="number"
name="numberIni"
placeholder="0"
class="form-control"
value={input_multi}
onChange={(event) => setInput_multi(event.target.value)}
/>
<br />
<button type="submit" className="btn btn-success"> <i class="far fa-save"></i></button>
<br />
<div class="col-sm-6">
<h6>2 - # input dynamic</h6>
<div class="input-group ">
<select name='numberIni2' class='form-control' onChange={handleInput_division}>
<option value='no' selected>
Seleccione </option>
<option value='2'> 2</option>
<option value='3'>3
</option>
</select>
<br/>
</div>
</div>
</div>
</div>
</div>
</form>
<br />
<div class="col-sm-12 btn btn-primary">
<b>PHASES</b>
</div>
<br /> <br />
<div class="row">
<div class="col-sm-12">
{numberIni && (
<div class="col-sm-12">
<label>
<font size="2">
1° PHASES <br />
select a number : {" "}
</font>
</label>
<select onChange={(e) => setSelect(e.target.value)} name="" id="">
<option value="seleccione">Seleccione</option>
{Array(parseInt(numberIni))
.fill(1)
.map((value, key) => {
return <option value={key + 1}>{key + 1} equipment</option>;
})}
</select>
<label>
<font size="2"> equipment </font>{" "}
</label>
{Array(parseInt(numberIni))
.fill(1)
.map((value, key2) => {
return (
<div>
{arraySelect[key2] && (
<>
<label>
<font size="2">
2° select another number <br />
classify: {" "}
</font>{" "}
</label>
<select
onChange={(e) => setSelect(e.target.value)}
name=""
id=""
>
<option value="seleccione">Seleccione</option>
{arraySelect[key2].map((value, key3) => {
return (
<option value={arraySelect[key2][key3]}>
{arraySelect[key2][key3]} equipment
</option>
);
})}
</select>
{rows.map((e, index) => (
<Row
nombre={e.nombre}
index={index}
onChange={(index, value) => handleOnChange(index, value)}
key={index}
/>
))}
</>
)}
</div>
);
})}
</div>
)}
</div>
</div>
{numberIni && (
<input
onClick={() => resetForm()}
type="button"
className="btn btn-danger"
value="restart phase"
/>
)}
</div>
);
}
export default Pruebas;
//Row2
const Row = (props) => {
const { onChange, onRemove, nombre, index } = props;
console.log(props);
return (
<div>
<input
disabled
value={nombre}
onChange={(e) => onChange(index, e.target.value)}
placeholder="Decrementar"
/>
</div>
);
};
export default Row;

Pagination issue in React.js

I've created Pagination component but have got issues while implementing it into my Characters component.
I'm getting prev and next buttons, but instead of page numbers I'm gettin NaN.
Please advise where is my mistake?
Is there an issue with Pagination props?
Pagination.js
import React, { useState } from "react";
export const Pagination = ({
data,
RenderComponent,
title,
pageLimit,
dataLimit,
}) => {
const [pages] = useState(Math.round(data.length / dataLimit));
const [currentPage, setCurrentPage] = useState(1);
function goToNextPage() {
setCurrentPage((page) => page + 1);
}
function goToPreviousPage() {
setCurrentPage((page) => page - 1);
}
const changePage = (event) => {
console.log(event.target);
const pageNumber = Number(event.target.textContent);
setCurrentPage(pageNumber);
};
const getPaginatedData = () => {
const startIndex = currentPage * dataLimit - dataLimit;
const endIndex = startIndex + dataLimit;
return data.slice(startIndex, endIndex);
};
const getPaginationGroup = () => {
let start = Math.floor((currentPage - 1) / pageLimit) * pageLimit;
return new Array(pageLimit).fill().map((_, idx) => start + idx + 1);
};
return (
<div>
<h1>{title}</h1>
<div>
{getPaginatedData().map((d, idx) => (
<RenderComponent key={idx} data={d} />
))}
</div>
<div className="pagination">
<button
onClick={goToPreviousPage}
className={`prev ${currentPage === 1 ? "disabled" : ""}`}
>
prev
</button>
{/* show page numbers */}
{getPaginationGroup().map((item, index) => (
<button
key={index}
onClick={changePage}
className={`paginationItem ${
currentPage === item ? "active" : null
}`}
>
<span>{item}</span>
</button>
))}
{/* next button */}
<button
onClick={goToNextPage}
className={`next ${currentPage === pages ? "disabled" : ""}`}
>
next
</button>
</div>
</div>
);
};
The file where I want to implement the Pagination component.
Characters.js
import { useState, useEffect } from "react";
import { CHARACTERS_PAGE_URL } from "../../api/rickNMortyApi";
import { Loading } from "../../components/Loading/Loading";
import { Character } from "./Character";
import { Pagination } from "../Pagination/Pagination";
export const Characters = () => {
const [characters, setCharacters] = useState();
useEffect(() => {
try {
fetch(CHARACTERS_PAGE_URL)
.then((res) => res.json())
.then(({ results }) => {
if (results && Array.isArray(results)) {
setCharacters(results);
}
})
.catch((err) => console.log(err));
} catch (e) {
console.log(e);
}
}, []);
if (!characters) {
return <Loading />;
}
return (
<div className="p-4 font-mono text-green-500 ">
<div className="flex flex-row">
<div className="m-4 ">
<label>Species</label>
<select name="species" id="species">
<option value="all">all</option>
<option value="human">human</option>
<option value="alien">alien</option>
</select>
</div>
<div className="m-4">
<label>Status</label>
<select name="status" id="status">
<option value="all">all</option>
<option value="alive">alive</option>
<option value="dead">dead</option>
<option value="unknown">unknown</option>
</select>
</div>
<div className="m-4">
<label>Gender</label>
<select name="gender" id="gender">
<option value="all">all</option>
<option value="female">female</option>
<option value="male">male</option>
<option value="genderless">genderless</option>
<option value="unknown">unknown</option>
</select>
</div>
</div>
<h1 className="text-4xl">Characters</h1>
<Pagination data={characters} />
<div className="grid grid-flow-col grid-cols-5 grid-rows-4 gap-4">
{characters.map((character) => (
<div key={character.id}>
<Character character={character} />
</div>
))}
</div>
</div>
);
};
I've added
and now I can see prev, 1, 2, 3, 4,5, next
but charcters do not change if I click on the page number
When I try to add dataLimit={20} as a props for Pagination I'm getting an arrow below:
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Characters filter by property value in React.js

I'm a trying to build an app based on Rick and Morty api.
I want to filter characters by species.
I've created separate components for each species value
For example:
Human.js
export const Human = ({ match }) => {
const { species } = match.params;
const [characterFilters, setCharacterFilters] = useState([]);
useEffect(() => {
try {
fetch('https://rickandmortyapi.com/api/character?species=human')
.then((res) => res.json())
.then((res) => setCharacterFilters(res))
.catch((err) => console.log(err));
} catch (e) {
console.log(e);
}
}, []);
const { name, image } = characterFilters;
return (
<div>
<h2>Name: {name}</h2>
<div>
<img alt={name} src={image}></img>
</div>
</div>
);
};
In the characters file I've set the conditions based on select propery chosen
Characters.js
export const Characters = () => {
const [characters, setCharacters] = useState();
useEffect(() => {
try {
fetch(CHARACTERS_PAGE_URL)
.then((res) => res.json())
.then(({ results }) => {
if (results && Array.isArray(results)) {
setCharacters(results);
}
})
.catch((err) => console.log(err));
} catch (e) {
console.log(e);
}
}, []);
const handleSpeciesChange = (e) => {
console.log("[e.target.value]", e.target.value);
switch (e.target.value) {
case "human":
return <Human />;
break;
case "alien":
return <Alien />;
break;
case "unknown":
return <Unknown />;
break;
default:
return;
}
};
const handleStatusChange = (e) => {
switch (e.target.value) {
case "alive":
return <Human />;
break;
case "dead":
return <Alien />;
break;
case "unknown":
return <Unknown />;
break;
default:
return;
}
};
if (!characters) {
return <Loading />;
}
return (
<div className="p-4 font-mono text-green-500 ">
<div className="flex flex-row">
<div className="m-4 ">
<label>Species</label>
<select name="species" id="species" onChange={handleSpeciesChange}>
<option value="all">all</option>
<option value="human">human</option>
<option value="alien">alien</option>
<option value="unknown">unknown</option>
</select>
</div>
<div className="m-4">
<label>Status</label>
<select name="status" id="status" onChange={handleStatusChange}>
<option value="all">all</option>
<option value="alive">alive</option>
<option value="dead">dead</option>
<option value="unknown">unknown</option>
</select>
</div>
<div className="m-4">
<label>Gender</label>
<select name="gender" id="gender">
<option value="all">all</option>
<option value="female">female</option>
<option value="male">male</option>
<option value="genderless">genderless</option>
<option value="unknown">unknown</option>
</select>
</div>
</div>
<h1 className="text-4xl">Characters</h1>
<Pagination data={characters} pageLimit={5} />
<div className="grid grid-flow-col grid-cols-5 grid-rows-4 gap-4">
{characters.map((character) => (
<div key={character.id}>
<Character character={character} />
</div>
))}
</div>
</div>
);
};
But I'm not getting filtered characters.
I'm new to React.
Please help me to understand, what am I doing wrong here?
Is there a possibility to created a common filter component that I would be able to apply for different properties filters?
You cannot return jsx from a callback
Make filters get stored and only render these values from the array:
export const Characters = () => {
const [characters, setCharacters] = useState();
const [ speciesFilter, setSpeciesFilter ] = useState('');
const [ status, setStatus] = useState('');
useEffect(() => {
try {
fetch(CHARACTERS_PAGE_URL)
.then((res) => res.json())
.then(({ results }) => {
if (results && Array.isArray(results)) {
setCharacters(results);
}
})
.catch((err) => console.log(err));
} catch (e) {
console.log(e);
}
}, []);
const handleSpeciesChange = (e) => {
console.log("[e.target.value]", e.target.value);
setSpeciesFilter(e.target.value)
};
const handleStatusChange = (e) => {
setStatus(e.target.value);
};
if (!characters) {
return <Loading />;
}
let filteredCharacters = characters;
if (speciesFilter) {
filteredCharacters = filteredCharacters.filter(c => c.species === speciesFilter);
}
if (status ) {
filteredCharacters = filteredCharacters.filter(c => c.status === status);
}
return (
<div className="p-4 font-mono text-green-500 ">
<div className="flex flex-row">
<div className="m-4 ">
<label>Species</label>
<select name="species" id="species" onChange={handleSpeciesChange}>
<option value="all">all</option>
<option value="human">human</option>
<option value="alien">alien</option>
<option value="unknown">unknown</option>
</select>
</div>
<div className="m-4">
<label>Status</label>
<select name="status" id="status" onChange={handleStatusChange}>
<option value="all">all</option>
<option value="alive">alive</option>
<option value="dead">dead</option>
<option value="unknown">unknown</option>
</select>
</div>
<div className="m-4">
<label>Gender</label>
<select name="gender" id="gender">
<option value="all">all</option>
<option value="female">female</option>
<option value="male">male</option>
<option value="genderless">genderless</option>
<option value="unknown">unknown</option>
</select>
</div>
</div>
<h1 className="text-4xl">Characters</h1>
<Pagination data={characters} pageLimit={5} />
<div className="grid grid-flow-col grid-cols-5 grid-rows-4 gap-4">
{filteredCharacters.map((character) => (
<div key={character.id}>
<Character character={character} />
</div>
))}
</div>
</div>
);
};
The above example uses a filter which can be improved
what am I doing wrong here?
You are returning JSX from the callback, for example,
onChange={handleStatusChange}
Here you pass the function which will be passed the event for you to handle, the problem is, returning a component from this function doesn't do anything, it doesn't tell React to render the component you returned.
Instead, you can store the value from there in state, and do something accordingly, for example, filter the array using that value
Is there a possibility to created a common filter component that I
would be able to apply for different properties filters?
That can be done, by passing the characters to that component and the filter values
export const FilterCharacters = ({ characters, status, specie }) => {
let filteredCharacters = characters;
if (specie ) {
filteredCharacters = filteredCharacters.filter(c => c.species === specie);
}
if (status ) {
filteredCharacters = filteredCharacters.filter(c => c.status === status);
}
return filteredCharacters.map((character) => (
<div key={character.id}>
<Character character={character} />
</div>
))
}
As for your Human and specific species components, it calls the API for filtered values, but I assume you already got all values initially, so you could only filter from there, if that's not the case, you could make Human more generic by passing the species and status, and querying the API with that values

Filter fetch data react

Why filter by search work but by drop-down list not?
I don't know why this is so, maybe someone sees some error.
I would like to filter tags using checkboxes. It was hard for me to find a tutorial on the internet, I was able to find filtering by searching. It turned out that everything was set up successfully, then I wanted to set filtering by list, but here I have a problem. I don't know why the list search doesn't work - even though it seems to work on the console.
demo here:
https://codesandbox.io/s/adoring-wu-rt4wd?file=/src/styles.css
const [filterParam, setFilterParam] = useState(['All'])
const [q, setQ] = useState('')
const [searchParam] = useState(['tags'])
function search(data) {
return data.filter((item) => {
if (item.tags == filterParam) {
return searchParam.some((newItem) => {
return (
item[newItem].toString().toLowerCase().indexOf(q.toLowerCase()) > -1
)
})
} else if (filterParam == 'All') {
return searchParam.some((newItem) => {
return (
item[newItem].toString().toLowerCase().indexOf(q.toLowerCase()) > -1
)
})
}
})
}
return (
<>
<div>
<label htmlFor='search-form'>
<input
type='search'
name='search-form'
id='search-form'
className='search-input'
placeholder='Search for...'
value={q}
onChange={(e) => setQ(e.target.value)}
/>
<span className='sr-only'>Search countries here</span>
</label>
</div>
<div className='select'>
<select
onChange={(e) => {
setFilterParam(e.target.value)
// console.log(setFilterParam(e.target.value.toString()))
console.log(e.target.value.toString())
}}
aria-label='Filter Countries By Region'
>
<option value='All'>All</option>
<option value='accessibility'>accessibility</option>
<option value='javascript'>javascript</option>
<option value='css'>css</option>
<option value='advanced'>advanced</option>
<option value='svg'>svg</option>
</select>
</div>
<section className={styles.main}>
{search(data).map((item) => (
<div className={styles.card}>
<div>
<div className={styles.card__first}>
<div className={styles.card__name}>
<FaTwitter className={styles.card__icon} />
<span className={styles.card__author}>{item.authorId}</span>
</div>
<div className={styles.card__price}>
<p>{item.price}</p>
</div>
</div>
<div className={styles.card__title}>
<h1>{item.title}</h1>
</div>
<div>
<p className={styles.card__desc}>{item.description}</p>
</div>
</div>
<div className={styles.card__tags}>
{item.tags.map((t) => {
return (
<div className={styles.card__tag}>
<p>{t}</p>
</div>
)
})}
</div>
</div>
))}
</section>
</>
)
}
export default Page
You have to change a lot of things, you can try this example
import "./styles.css";
import { useState, useEffect } from "react";
import styles from "./App.module.css";
export default function App() {
const [data, setData] = useState([]);
const [filterParam, setFilterParam] = useState("All");
const [q, setQ] = useState("");
const [searchParam, setSearchParam] = useState([]);
const getData = () => {
fetch("data.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json"
}
})
.then(function (response) {
console.log(response);
return response.json();
})
.then(function (myJson) {
console.log(myJson);
setData(myJson);
});
};
useEffect(() => {
getData();
}, []);
function search(data) {
return data.filter(
(item) =>
(filterParam === "All" || item.tags.includes(filterParam)) &&
(searchParam.length === 0 ||
(searchParam.every((tag) => item.tags.includes(tag)) &&
JSON.stringify(item).toLowerCase().indexOf(q.toLowerCase()) > -1))
);
}
const inputChangedHandler = (event) => {
const value = event.target.value;
const index = searchParam.indexOf(value);
if (index > -1) {
const updatedParam = [...searchParam];
updatedParam.splice(index, 1);
setSearchParam(updatedParam);
} else {
setSearchParam([...searchParam, event.target.value]);
}
};
return (
<>
<div>
<label htmlFor="search-form">
<input
type="search"
name="search-form"
id="search-form"
className="search-input"
placeholder="Search for..."
value={q}
onChange={(e) => setQ(e.target.value)}
/>
<span className="sr-only">Search countries here</span>
</label>
</div>
<div className="select">
<select
onChange={(e) => {
setFilterParam(e.target.value);
// console.log(setFilterParam(e.target.value.toString()))
console.log(e.target.value.toString());
}}
aria-label="Filter Countries By Region"
>
<option value="All">All</option>
<option value="accessibility">accessibility</option>
<option value="javascript">javascript</option>
<option value="css">css</option>
<option value="advanced">advanced</option>
<option value="svg">svg</option>
</select>
</div>
<div>
<input
type="checkbox"
id="topping"
name="advanced"
value="advanced"
onChange={inputChangedHandler}
/>
advanced
</div>
<div>
<input
type="checkbox"
id="topping"
name="javascript"
value="javascript"
onChange={inputChangedHandler}
/>
javascript
</div>
<div>
<input
type="checkbox"
id="topping"
name="fundamentals"
value="fundamentals"
onChange={inputChangedHandler}
/>
fundamentals
</div>
<div>
<input
type="checkbox"
id="topping"
name="css"
value="css"
onChange={inputChangedHandler}
/>
css
</div>
<div>
<input
type="checkbox"
id="topping"
name="svg"
value="svg"
onChange={inputChangedHandler}
/>
svg
</div>
<div>
<input
type="checkbox"
id="topping"
name="accessibility"
value="accessibility"
onChange={inputChangedHandler}
/>
accessibility
</div>
<section className={styles.main}>
{search(data).map((item) => (
<div className={styles.card}>
<div>
<div className={styles.card__first}>
<div className={styles.card__name}>
<p className={styles.card__icon}>ICON</p>
<span className={styles.card__author}>{item.authorId}</span>
</div>
<div className={styles.card__price}>
<p>{item.price}</p>
</div>
</div>
<div className={styles.card__title}>
<h1>{item.title}</h1>
</div>
<div>
<p className={styles.card__desc}>{item.description}</p>
</div>
</div>
<div className={styles.card__tags}>
{item.tags.map((t) => {
return (
<div className={styles.card__tag}>
<p>{t}</p>
</div>
);
})}
</div>
</div>
))}
</section>
{/* <Margins>
<Header data={data} />
<Main data={data} />
</Margins> */}
</>
);
}
enter link description here

Resources