I have the following component which transforms checkbox into nice toggle switch
const ToggleSwitch = forwardRef((props, ref) => {
return (
<div className={`toggle btn btn-lg>
<input type='checkbox' onChange={handleOnChange} ref={ref} />
<div className='toggle-group'>
<label htmlFor={`toggle-${uniqueId}`} className={`btn btn-success btn-lg toggle-on`} ref={labelOn}>In Use</label>
<label htmlFor={`toggle-${uniqueId}`} className={`btn btn-danger btn-lg toggle-off`} ref={labelOff}>Not in Use</label>
<span className={`toggle-handle btn btn-light btn-lg`} ref={handle}></span>
</div>
</div>
);
});
Iam having an issue understanding how forward ref works and iam getting some errors. It is possible as well that iam confused by HOC components too
If i called this from different component like this:
<ToggleSwitch checked={false} toggleName='monitoring' ref={(e) => {monitoring.current = e;register(e);}}/>
it works as expected without any issues. However if i call it as per below:
I have a table component which get data from body:
const body = [{ key: 'inUse', type: 'component', component: ToggleSwitch, props: { checked: 'inUse', onChange: onToggleChange } }, { key: 'vlan' }, { key: 'clientId' }];
Each key is column. Now in table component i have a switch based on type. If type = "component"
return <td>{component({ ...field.props, checked: entry[field.props.checked], entry: entry })}</td>
In here i get an error: Uncaught TypeError: component is not a function
Any help would be appreciated. I have looked through similar questions but couldnt find any solution. Thank you
You should not invoke your components directly, but pass them into createElement
function:
return (
<td>
{createElement(component, {
...field.props,
checked: entry[field.props.checked],
entry: entry,
})}
</td>
);
You can also use JSX here, but with JSX you will have to name your component
property with capital letter, so transformation would not confuse it with html or custom element.