I am writing a Web app using ReactJS and Typescript.
I wrote the following code inside my class
class FractionComponent extends React.Component<any, FractionState>{
constructor(props: any) {
super(props);
this.state = this.createNew();
}
renderBoard() {
const strBoardId = "board";
return (
<Board
id={strBoardId}
itemsRender={this.renderItems}
rowsNumber={this.state.rowsNumber}
columnsNumber={this.state.columnsNumber}
onClick={() => this.handleClick()}
/>
);
}
renderCell(id: string, coords: FractionCoord) {
return (
<div key={id} className="page_boardCell" />
);
}
renderItems(rows: number, columns: number) {
let rowsArray = [];
let columnsArray: string[] = [];
for (let i = 0; i < rows; i++) {
columnsArray = []
for (let j = 0; j < columns; j++) {
columnsArray.push(`${i}${j}`);
}
rowsArray.push(columnsArray)
}
return (
rowsArray.map((row, ri) => (
<div key={ri} className="page_boardRow">
{columnsArray.map((cellId, index) => this.renderCell(cellId, { "a": ri, "b": index })
)}
</div>
))
);
}
render() {
return (
<React.Fragment>
{this.renderBoard()}
</React.Fragment>
)
}
}
function Board(props: BoardProps) {
var classes = ["fractionPage_board"];
if (props.selected) { classes.push("fractionPage_selectedSquare"); }
if (props.isCellError) { classes.push("fractionPage_error"); }
return (
<div key={props.id} className={classes.join(" ")} onClick={props.onClick} style={{ ...props.cellStyle }}>
{props.itemsRender(props.rowsNumber, props.columnsNumber)}
</div>
);
}
interface BoardProps { id: string, onClick: any, itemsRender: any, columnsNumber: number, rowsNumber: number }
But it gives me this error
TypeError: this.renderCell is not a function
When I remove renderCell function and embedd the code directly in renderItems it works.
WHat's the problem could be?
Thank you.
EDIT
I forget to say that I am passingrenderItems as a props to another component.
The callback function passed inside map is an arrow function, in which this won't refer to the class instance. Change it to a regular function syntax, and things should work fine
{columnsArray.map(function(cellId, index) { return this.renderCell(cellId, { "a": ri, "b": index })})}