0

I'm trying to add a conditional CSS class to each day of the calendar: https://material-ui-pickers.dev/api/DatePicker

This prop seems to be the way:

renderDay(day: DateIOType, selectedDate: DateIOType, dayInCurrentMonth: boolean, dayComponent: Element) => Element

... but I'm not sure how to work with the dayComponent parameter

handleRenderDay = (day, selectedDate, dayInCurrentMonth, dayComponent) => {
    console.log(dayComponent)
    return dayComponent
}

When I console.log dayComponent, it's a simple object with "$$typeof": Symbol(react.element) as an attribute. How can I modify this object to add a CSS class to the element when the component is rendered?

Edit: React.isValidElement(dayComponent) returns true so that answers "What is this object?" that I was wondering about.

Matthew
  • 8,183
  • 10
  • 37
  • 65

1 Answers1

0

Ok, this question does help: React.cloneElement -> Add className element

Thanks for that @bertdida

I found out that the object I was wondering about is a valid React element so I'm cloning it and returning the new one which works.

handleRenderDay = (day, selectedDate, dayInCurrentMonth, dayComponent) => {
    console.log(React.isValidElement(dayComponent)) // this is a valid element
    const newDayComponent = React.cloneElement(dayComponent, {
        className: "exclaim" // this clobbers it's classes
    })
    console.log(dayComponent.props.className) // this is undefined
    return newDayComponent
}

The problem now is to preserve the existing classes and add one to them. With the above code, the days have now lost all their styling.

Alternatively, I can wrap the dayComponent with a div with my class so the original classes and element are preserved:

handleRenderDay = (day, selectedDate, dayInCurrentMonth, dayComponent) => {
    return (
        <div className="exclaim">
            {dayComponent}
        </div>
    )
}

I'm still learning React so I can't help thinking there should be a way to add (not clobber) classes to the element thereby preserving the intended styles.

Here is the doc that shows usage of the renderDay prop: https://material-ui-pickers.dev/demo/datepicker#dynamic-data

Matthew
  • 8,183
  • 10
  • 37
  • 65