Reputation: 8685
I have the following code
import React, {Component, useMemo } from "react";
class TimeslotPicker extends Component {
constructor(props) {
super(props);
this.state = {
error: '',
loading: false
};
}
createCalendar(year, month) {
let mon = month - 1; // months in JS are 0..11, not 1..12
let d = new Date(year, mon);
let table = '<div className="row">' +
'<div className="col">MON</div>' +
'<div classNAme="col">TUE</div>' +
'<div className="col">WED</div>' +
'<div className="col">THU</div>' +
'<div className="col">FRI</div>' +
'<div className="col">SAT</div>' +
'<div className="col">SUB</div>' +
'</div><div className="row">';
// spaces for the first row
// from Monday till the first day of the month
// * * * 1 2 3 4
for (let i = 0; i < this.getDay(d); i++) {
table += '<div className="col"></div>';
}
// <td> with actual dates
while (d.getMonth() == mon) {
table += '<div className="col">' + d.getDate() + '</div>';
if (this.getDay(d) % 7 == 6) { // sunday, last day of week - newline
table += '</div><div className="row">';
}
d.setDate(d.getDate() + 1);
}
// add spaces after last days of month for the last row
// 29 30 31 * * * *
if (this.getDay(d) != 0) {
for (let i = this.getDay(d); i < 7; i++) {
table += '<div className="col"></div>';
}
}
// close the table
table += '</div></div>';
return table;
}
getDay(date) { // get day number from 0 (monday) to 6 (sunday)
let day = date.getDay();
if (day == 0) day = 7; // make Sunday (0) the last day
return day - 1;
}
render () {
const calendar = this.createCalendar(2022, 9);
return (
{calendar}
)
}
}
export default TimeslotPicker;
I get the following error when running the code "Objects are not valid as a React child (found: object with keys {calendar}). If you meant to render a collection of children, use an array instead."
What am I doing wrong?
Upvotes: 0
Views: 71
Reputation: 1825
If you return single quotes or say backticks with string interpolation, react treats it as a string and not JSX. What you can do instead is
let table = (
<div className="row">
<div className="col">MON</div>
<div className="col">TUE</div>
<div className="col">WED</div>
<div className="col">THU</div>
<div className="col">FRI</div>
<div className="col">SAT</div>
<div className="col">SUB</div>
</div>
);
Or, you can use dangerouslySetInnerHTML to render HTML from a string with React
For the first approach here's link to codesandbox
Upvotes: 1