src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ReactJS </title>
</head>
<body>
<div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { useState } from 'react';
import './App.css';
const COUNTRY = [
{ id: 1, name: 'AFGHANISTAN'},
{ id: 2, name: 'ANGOLA'},
{ id: 3, name: 'ARGENTINA'},
{ id: 4, name: 'ARMENIA'},
{ id: 5, name: 'BOLIVIA'},
{ id: 6, name: 'CAMBODIA'},
{ id: 7, name: 'PHILIPPINES'},
{ id: 9, name: 'UNITED ARAB EMIRATES'},
{ id: 10, name: 'UNITED KINGDOM'},
{ id: 11, name: 'UNITED STATES'},
];
function App() {
const [name, setName] = useState('');
const [foundCOUNTRY, setFoundCOUNTRY] = useState(COUNTRY);
const filter = (e) => {
const keyword = e.target.value;
if (keyword !== '') {
const results = COUNTRY.filter((country) => {
return country.name.toLowerCase().startsWith(keyword.toLowerCase());
// toLowerCase() method to make it case-insensitive
});
setFoundCOUNTRY(results);
} else {
setFoundCOUNTRY(COUNTRY); // If the text field is empty, show all COUNTRY
}
setName(keyword);
};
return (
<div className="container">
<input
type="search"
value={name}
onChange={filter}
className="input"
placeholder="Filter"
/>
<div className="country-list">
{foundCOUNTRY && foundCOUNTRY.length > 0 ? (
foundCOUNTRY.map((country) => (
<li key={country.id} className="country">
<span className="country-name">{country.name}</span>
</li>
))
) : (
<h1>No results found!</h1>
)}
</div>
</div>
);
}
export default App;
src/App.css
//src/App.css
.container {
padding-top: 30px;
width: 300px;
margin: auto;
}
.input {
padding: 5px 15px;
width: 300px;
}
.country-list {
margin-top: 30px;
}
.country {
list-style: none;
margin: 10px 0;
padding: 10px;
background: #eee;
display: flex;
justify-content: space-between;
}
.country-id {
color: red;
margin-right: 20px;
}
.country-name {
color: blue;
}
