Reputation: 23
Need the card
component to communicate with the search
component to filter results.
At the moment the data
comes from a local JSON file with the following format
[
{
"title": "example",
"description": "example",
"author": "example",
"date": "2021-01-01",
"featuredImage": "/example.jpg",
"categories": "example",
"tags": "example",
}
]
App.js
import React, { useState } from 'react';
import Card from './components/Card';
import Search from './components/Search';
import Data from './data/data.json';
import './App.css';
const App = () => {
const [DataFile, setDataFile] = useState(Data);
const [Search, setSearch] = useState('');
const [Result, setResult] = useState([]);
const searchChange = (e) => {
setSearch(e.target.value);
};
const onSearch = () => {
setResult(Data);
};
return (
<>
<Search onChange={searchChange} onSearch={onSearch} />
<Card data={DataFile} Result={Result} />
</>
);
};
export default App;
Search.js
import React from 'react';
const Search = ({ onChange }) => (
<input
type='search'
placeholder='Search...'
className='search'
onChange={onChange}
/>
);
export default Search;
Card.js
import React from 'react';
const Card = ({ data }) => {
return (
<div className='container'>
{data.map((x) => (
<div >
<h1>{x.title}</h1>
</div>
))}
</div>
);
};
export default Card;
I've confused myself with the React hooks. Could someone please explain what I'm doing wrong with the state?
Upvotes: 2
Views: 1136
Reputation: 4838
i added the data to component to make it clear for you
const App = () => {
//here we define data
const data = [
{
"title": "example",
"description": "example",
"author": "example",
"date": "2021-01-01",
"featuredImage": "/example.jpg",
"categories": "example",
"tags": "example",
}
]
//here is where we keep search result
const [Result, setResult] = useState(null);
//here we filter the list where the title(or any element of data) is equal to input value
const searchChange = (e) => {
const searchResult = data.filter((element) => element.title
.includes(e.target.value))
//here we set the filtered list to result
setResult(searchResult);
};
return (
<>
<Search onChange={searchChange}/>
//here we check if result exists if yes pass it to card else pass the data instead
<Card data={Result!==null?Result:data}/>
</>
);
};
i commented the information about the code so you can read them
Upvotes: 1