I have just finished this blog post tutorial ReactCalendarComponent and now I am trying to separate the long one page component that the tutorial provides into different components. I am new to React so I start reading post about which is the best way to handle data beetween parents and children components; and I conclude that redux was to much for this proyect, so I try to only use react Hooks. (Correct me, please, if the decision was bad). Finally I get to a Point that my Proyect is separated into differents components, but the parent continue to have all the functions that are related to the state and the child components.
Parent component
import MonthTable from "./components/MonthTable"
import YearTable from "./components/YearTable"
import DateTable from "./components/DateTable"
import ShowHeader from "./components/ShowHeader"
import moment from "moment";
const DateObjectContext = React.createContext();
const Calendar = () => {
const weekdayshort = moment.weekdaysShort();
const [dateObject, setDateObject] = useState(moment());
const [allMonths, setAllMonths] = useState(moment.months());
const [selectedDay, setSelectedDay] = useState(0)
const [showDateTable, setShowDateTable] = useState(true)
const [showMonthTable, setShowMonthTable] = useState(false)
const [showYearTable, setShowYearTable] = useState(false)
//Long list of functions that handles the child components and the state
//Here are some
let month = () => ( dateObject.format("MMMM") )
const handleShowYearTable = (e) => {
if(showMonthTable === true){
setShowYearTable(false)
}else if(showDateTable === true){
setShowDateTable(false)
}
setShowYearTable(true)
}
return (
<div className="tail-datetime-calendar">
<DateObjectContext.Provider value={{
month,
showMonth,
onPrev,
onNext,
handleShowYearTable,
year,
}}>
<ShowHeader />
</DateObjectContext.Provider>
<div className="calendar-date">
{
<DateObjectContext.Provider
value={{
allMonths,
setMonth,
actualYear,
setYear
}}>
{showYearTable && <YearTable props={year()}/>}
{showMonthTable && <MonthTable />}
</DateObjectContext.Provider>
}
</div>
<div>
<DateObjectContext.Provider
value={{
weekdayshort,
daysInMonth,
firstDayOfMonth,
currentDay,
onDayClick
}}>
{showDateTable && <DateTable />}
</DateObjectContext.Provider>
</div>
</div>
);
}
Example of one child, ShowHeader
const ShowHeader = () => {
const { month,
showMonth,
onPrev,
onNext,
handleShowYearTable,
year} = useContext(DateObjectContext)
return (
<div className="calendar-navi">
<span
className="calendar-button button-prev"
onClick={e => onPrev()}></span>
<span
data-tail-navi="switch"
className="calendar-label"
onClick={ e => {showMonth()} }>
{month()}
</span>
<span
className="calendar-label"
onClick={e => handleShowYearTable()}>
{year()}
</span>
<span
className="calendar-button button-next"
onClick={e => {onNext()}}></span>
</div>
)
}
My Question is: ¿How can I put the functions related to the child components inside each component?