I am having trouble with React js. I am implementing search functionality. Everything is good but I want to show if the term entered in the search bar is not available. It should show "No Data Found". I have also attached the screenshot.
Search Component
const UserDetails = () => {
const [posts, setPosts] = useState([]);
const [searchTerm, setSearchTerm] = useState("");
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => setPosts(data.results));
}, []);
return (
<>
<div className="Navbar">
<img className="logo" src={logo} alt="" />
<input
type="text"
onChange={(event) => {
setSearchTerm(event.target.value);
}}
placeholder="Search User.."
></input>
</div>
<div className="card">
{posts.length > 0 ? (
posts
.filter((val) => {
if (searchTerm === "") {
return val;
} else if (
val.name.first
.toLowerCase()
.includes(searchTerm.toLowerCase()) ||
val.name.last.toLowerCase().includes(searchTerm.toLowerCase())
) {
return val;
}
})
.map((post, index) => <Userdetail key={index} post={post} />)
) : (
<div className="loading">
<img src={logo} className="App-logo" alt="logo" />
<p className="loading-data">Loading Data...</p>
</div>
)}
</div>
</>
);
};
export default UserDetails;
You are checking if posts has values, and if it doesn't it should show loading div. This is the place where you should add "No data found" and for the loading you should set state to indicate loading status.
I have modified your code a bit
const UserDetails = () => {
const [posts, setPosts] = useState([]);
const [searchTerm, setSearchTerm] = useState("");
const [loading,setLoading] = useState(false) // loading state
useEffect(() => {
setLoading(true); // loading started
fetch(url)
.then((res) => res.json())
.then((data) => {
setPosts(data.results);
setLoading(false); // loading stopped
})
.catch((e) => {
setLoading(false); // loading stopped
console.log(e);
});
}, []);
return (
<>
<div className="Navbar">
<img className="logo" src={logo} alt="" />
<input
type="text"
onChange={(event) => {
setSearchTerm(event.target.value);
}}
placeholder="Search User.."
></input>
</div>
<div className="card">
{loading ? ( // loading state
<div className="loading">
<img src={logo} className="App-logo" alt="logo" />
<p className="loading-data">No data</p>
</div>
) : posts.length > 0 ? (
posts
.filter((val) => {
if (searchTerm === "") {
return val;
} else if (
val.name.first
.toLowerCase()
.includes(searchTerm.toLowerCase()) ||
val.name.last.toLowerCase().includes(searchTerm.toLowerCase())
) {
return val;
}
})
.map((post, index) => <Userdetail key={index} post={post} />)
) : (
<p>No data found!</p>
)}
</div>
</>
);
};
export default UserDetails;