I am new to ReactJS and doing some hands on practice. I am working on a page where two tables are present and have linked data. I am looking for some suggestion around on how to communicate dependent data state to multiple elemnts in sibling component
I've created tables for each as components and kept them under main component.
import React from 'react'
import Professor from '../Professor';
import Student from '../Student'
function Main() {
return (
<div className="w3-row-padding">
<div className="w3-half"> <Professor /> </div>
<div className="w3-half"> <Student /> </div>
</div>
);
}
Here is sample code for Professor component:
import teachers from "./teachers.json";
class Professor extends Component{
constructor(props) {
super(props);
this.state = {
};
}
renderHeader = () => {
let headerElement = ['name', 'present']
return headerElement.map((key, index) => {
return <th key={index}>{key}</th>
})
}
renderBody = () => {
return teachers && teachers.map(({ StaffID, StaffName, RoleID, Present }) => {
return (
<tr key={StaffID}>
<td>{StaffName}</td>
<td style={{verticalAlign: "middle"}}>
<input type="checkbox" name={StaffName} defaultChecked={Present ? 'checked' : false}
/>
</td>
</tr>
)
})
}
render() {
return (
<div>
<table>
<thead>
<tr>{this.renderHeader()}</tr>
</thead>
<tbody>
{this.renderBody()}
</tbody>
</table>
</div>
)
}
}
export default Professor;
Similarly I have another table for students listing data from student json containing student name and professor id.
In professor table, user can mark presence of professor using checkbox. And on click of checkbox from Professors table, I want to update all rows in Student table with either alternate staff or a message. In this case, I need to establish sibling component communication and update mulitiple rows in sibling table on an event. Any idea on how this can be achieved will be helpful.
Thanks
You need to lift up your state to the parent component
import { useState } from "React"
import ...
function Main() {
[teacherIsPresent, setTeacherIsPresent] = useState(false)
const toggleTeacherPresence = () => {
setTeacherIsPresent((previousState) => !previousState)
}
return (
<div className="w3-row-padding">
<div className="w3-half"> <Professor toggleTeacherPresence={toggleTeacherPresence} teacherIsPresent={teacherIsPresent}/> </div>
<div className="w3-half"> <Student /> </div>
</div>
);
}
in your child component:
class Professor extends Component{
// your code
<input type="checkbox" name={StaffName} defaultChecked={this.teacherIsPresent ? 'checked' : false} onChange{this.props.toggleTeacherPresence}
/>
// your other code
}
You should consider to use functional components as Childs - since you do it in the parent anyways. This would make things easier...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.