24
loading...
This website collects cookies to deliver better user experience
Note!. If you do not know how to create a react app, check out this video
npm install @mui/material
import { React, useState } from "react";
import TextField from "@mui/material/TextField";
import List from "./Components/List"
import "./App.css";
function App() {
return (
<div className="main">
<h1>React Search</h1>
<div className="search">
<TextField
id="outlined-basic"
variant="outlined"
fullWidth
label="Search"
/>
</div>
<List />
</div>
);
}
export default App;
.main {
display: flex;
height: 100vh;
width: 100%;
align-items: center;
flex-direction: column;
row-gap: 20px;
}
h1 {
margin: 10px;
font-size: 40px;
color: rgb(1, 1, 59);
}
.search {
width: 30%;
}
ul li {
font-size: 20px;
}
[{
"id": 1,
"text": "Devpulse"
}, {
"id": 2,
"text": "Linklinks"
}, {
"id": 3,
"text": "Centizu"
}, {
"id": 4,
"text": "Dynabox"
}, {
"id": 5,
"text": "Avaveo"
}, {
"id": 6,
"text": "Demivee"
}, {
"id": 7,
"text": "Jayo"
}, {
"id": 8,
"text": "Blognation"
}, {
"id": 9,
"text": "Podcat"
}, {
"id": 10,
"text": "Layo"
}]
import { React, useState } from 'react'
import data from "./ListData.json"
function List(props) {
return (
<ul>
{data.map((item) => (
<li key={item.id}>{item.text}</li>
))}
</ul>
)
}
export default List
Note: Always convert the input text to lower case when creating a search bar.
import { React, useState } from "react";
import TextField from "@mui/material/TextField";
import List from "./Components/List";
import "./App.css";
function App() {
const [inputText, setInputText] = useState("");
let inputHandler = (e) => {
//convert input text to lower case
var lowerCase = e.target.value.toLowerCase();
setInputText(lowerCase);
};
return (
<div className="main">
<h1>React Search</h1>
<div className="search">
<TextField
id="outlined-basic"
onChange={inputHandler}
variant="outlined"
fullWidth
label="Search"
/>
</div>
<List input={inputText} />
</div>
);
}
export default App;
import { React, useState } from 'react'
import data from "./ListData.json"
function List(props) {
//create a new array by filtering the original array
const filteredData = data.filter((el) => {
//if no input the return the original
if (props.input === '') {
return el;
}
//return the item which contains the user input
else {
return el.text.toLowerCase().includes(props.input)
}
})
return (
<ul>
{filteredData.map((item) => (
<li key={item.id}>{item.text}</li>
))}
</ul>
)
}
export default List