I am new to react-router. I’ve set some data as JSON data in the public folder and shown some of them using the slice function and wanted to show more data on click the "see more" button. I’ve done the first part but cannot figure out how to do the rest on the button click. please help me to figure it out.
import React from 'react';
import './Home.css'
import Banner from '../Banner/Banner';
import { useLoaderData } from 'react-router-dom';
import Job from '../Job/Job';
const Home = () => {
let jobs = useLoaderData();
console.log(jobs);
const jobsLoader = jobs;
if (jobs.length > 6) {
jobs = jobs.slice(0, 6)
}
const handleSeeMore = () => {
console.log(jobsLoader);
}
return (
<div className='home-container'>
<Banner></Banner>
<div className="jobs-container">
<div className='featured-jobs-heading'>
<h2>Featured Jobs</h2>
<p>Explore thousands of job opportunities with all the information you need. Its your future</p>
</div>
<div className='job-container'>
{
jobs.map(job => <Job
key={job.id}
job={job}
></Job>)
}
</div>
<button onClick={()=>handleSeeMore()} className='see-more'>See More</button>
</div>
</div>
);
};
export default Home;
2
Answers
You would need to add a
useState
to make this happen. The idea is to add number of jobs as a state and callsetState
when the button is clicked.Your component would look like this
This works because
setJobCount
causes a rerender of the component. Thus, the component loads after the button click withjobCount
set to12
.You will need to handle it using state, I have changed your code to work as you want:
The state jobCount will determine how many items to show. In the initial useEffect we are setting the first ending point for the array which would be 6 in case there are more than six items otherwise it will be set to the number of items (i.e length ). Also I have set a condition on see more button that it will only show when there items left to display otherwise it will not show.
Then in our handleSeeMore funtion, we are checking if the addition of 6 more items exceed our total items, if it does then we will show all the remaining items otherwise we will show 6 more items.