Reputation: 2149
Hi I am having some problems with a react project, I am working with hooks and I am getting a problem witha method passed as a prop to the hook. I am using materail ui as well, this is my code:
import { Container, Grid, Select, MenuItem } from '@material-ui/core';
import React, { Component } from 'react';
import Store from '../component/store/store'
class StoreBuilder extends Component {
state = {
DivisionState: 'Store 1',
DivisionData: [
{
id: 1,
divDeptShrtDesc: 'Store 1'
},
{
id: 2,
divDeptShrtDesc: 'Store 2'
},
{
id: 3,
divDeptShrtDesc: 'Store 3'
}
]
};
handleChangeDivision(event) {
this.setState({ DivisionState: event.target.value });
}
renderDivisionOptions() {
return this.state.DivisionData.map((dt, i) => {
return (
<MenuItem
key={i}
value={dt.divDeptShrtDesc}>
{dt.divDeptShrtDesc}
</MenuItem>
);
});
}
render() {
return (
<div>
<Container >
<Grid >
<Store stores={this.state.DivisionState}
onChange={this.handleChangeDivision}
render ={this.renderDivisionOptions()}>
</Store>
</Grid>
</Container>
</div>
);
}
}
export default StoreBuilder;
The next is the hook code:
import { Container, Grid, Select, MenuItem } from '@material-ui/core';
import React, { Component } from 'react';
const store = (props) => {
return (
<div>
<Container >
<Grid >
<Select value={props.DivisionState}
onChange={props.handleChangeDivision}
>
{() =>props.render()}
</Select>
</Grid>
</Container>
</div>
);
}
export default store;
The issue is in the next code, I'm not pretty sure if it is possible to do the next code, I'm trying to pass the renderDivisionOptions method as a param to be used in the hook with the props:
{() =>props.render()}
Upvotes: 9
Views: 25014
Reputation: 191976
You are passing a function {() =>props.render()}
to the <Select>
, but it seems that you need to call the function instead:
<Select value={props.DivisionState}
onChange={props.handleChangeDivision}
>
{props.render()}
</Select>
In addition, if the Select
element expects a ReactNode, you might need to wrap it with a fragment:
<>{props.render()}</>
Since you pass renderDivisionOptions
as a callback to another component, it loses its context (this
). You need to convert it to an arrow function, or bind it in the constructor.
renderDivisionOptions = () => {
return this.state.DivisionData.map((dt, i) => {
return (
<MenuItem
key={i}
value={dt.divDeptShrtDesc}>
{dt.divDeptShrtDesc}
</MenuItem>
);
});
}
Upvotes: 5