Skip to content

Instantly share code, notes, and snippets.

@ManishPoduval
Created February 24, 2021 08:36
Show Gist options
  • Save ManishPoduval/866872004685b698946c30f977b50fd0 to your computer and use it in GitHub Desktop.
Save ManishPoduval/866872004685b698946c30f977b50fd0 to your computer and use it in GitHub Desktop.
import React, { Component, useState } from 'react'
import studentsJson from '../students.json'
import StudentDetails from './StudentDetails'
function Students() {
const [students, updateStudents] = useState(studentsJson.slice(0,5))
const handleSort = () => {
console.log('Sort works')
//always clone the arr before mutating it
let clonedStudents = JSON.parse(JSON.stringify(students))
clonedStudents.sort((first, second) => {
if (first.name > second.name) {
return 1
}
else if (first.name < second.name) {
return -1
}
else {
return 0
}
})
//always make sure you update the state so that it can re-render
updateStudents(clonedStudents)
}
const handleAdd = () => {
let randomIndex = Math.floor(Math.random() * studentsJson.length )
let randomStudent = studentsJson[randomIndex]
updateStudents([...students, randomStudent])
}
const handleDelete = (studentId) =>{
console.log('Delete')
// filter all students that dont match that id
let filteredStudents = students.filter((singleStudent) => {
return singleStudent.id !== studentId
})
updateStudents(filteredStudents)
}
return (
<div>
<h1>Students</h1>
<button onClick={handleSort} >Sort</button>
<button onClick={handleAdd} >Add</button>
{
// always use a map and return a JSX element
students.map((singleStudent, index) => {
// always pass the key prop for React to uniquely identify elements rendered in a loop
return <StudentDetails
key={index}
name={singleStudent.name}
city={singleStudent.city}
id={singleStudent.id}
onDelete={handleDelete}
/>
})
}
</div>
)
}
export default Students
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment