I'm passing an array of objects from external js file to the main component to render:
const students = filteredStudents.map(i =>
<div key={i.id} className='d-flex border-bottom'>
<img src={i.pic} className='align-self-center border rounded-circle mx-4' />
<div className='my-3'>
<h2 className='fw-bold'>{i.firstName.toUpperCase()} {i.lastName.toUpperCase()}</h2>
<div className='text-secondary ms-4'>
<p className='mb-0'>Email: {i.email}</p>
<p className='mb-0'>Company: {i.company}</p>
<p className='mb-0'>Skill: {i.skill}</p>
<p className='mb-0'>Average: {getAverageScore(i.grades)}%</p>
<div className='mt-2 d-none'>
{getGrades(i.grades)}
</div>
</div>
</div>
// Here is a button
</div>
);
return students;
main component render:
const items = renderStudents(this.state.query, this.state.students);
return (
<div id='students-card' className='overflow-auto border shadow-lg'>
<input className='w-100' placeholder='Search by name' onChange={this.handleChange} value={this.state.query} />
{items} // Array of objects being rendered here
</div>
);
Imagine there is a button instead of comment and when user clicks on it then d-none
should be toggled on and off. I got completely stuck on this. Should I render every student object like a single component with it's state rather then my way?
CodePudding user response:
You can assign an id and store it to a local state, use it as identifier for the current selected item and you can do your logic.
Check below example
const [selectedGrade, setGrade] = React.useState(null)
const [show, setShow] = React.useState(true)
const handleHideShowGrade = (id) => {
setGrade(id)
setShow(!show)
}
const students = filteredStudents.map((i, idx) =>
<div key={i.id} className='d-flex border-bottom'>
<img src={i.pic} className='align-self-center border rounded-circle mx-4' />
<div className='my-3'>
<h2 className='fw-bold'>{i.firstName.toUpperCase()} {i.lastName.toUpperCase()}</h2>
<div className='text-secondary ms-4'>
<p className='mb-0'>Email: {i.email}</p>
<p className='mb-0'>Company: {i.company}</p>
<p className='mb-0'>Skill: {i.skill}</p>
<p className='mb-0'>Average: {getAverageScore(i.grades)}%</p>
<div className={`mt-2 ${selectedGrade === idx && show ? '' : 'd-none'}`}>
{getGrades(i.grades)}
</div>
</div>
</div>
// Here is a button
<button onclick={() => handleHideShowGrade(idx)}
</div>
);
return students;