I have view component, which have to import multiple component. Those component are going to be rendered according to some specific condition. How it should work is that I got 3 buttons on page, for example after I click on first button (file upload) I need to render <FileImport>
component down below. What component should be rendered is in renderImportAttributes
function. But it throws me a warning
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
What exactly is wrong with this?
export default class ImportView extends React.PureComponent<ModelYearListProps, IState> {
constructor(props) {
super(props);
this.state = {
selectedImportOption: null
}
}
private selectImportOption(option: string): any {
this.setState(prevState => ({
selectedImportOption: option,
}));
}
private renderImportAttributes(): JSX.Element {
if (this.state.selectedImportOption === FILE_IMPORT) {
return <FileImport history={this.props.history} importerId={this.props.match.params.importerId} />;
}
else if (this.state.selectedImportOption === SPIDER_IMPORT) {
//another component
}
else if (this.state.selectedImportOption === URL_IMPORT) {
//another component
}
return null;
}
render() {
return (
<div className="overView">
<Button onClick={() => this.selectImportOption(FILE_IMPORT)}>
File
</Button>
<Button onClick={() => this.selectImportOption(SPIDER_IMPORT)}>
Spider
</Button>
<Button onClick={() => this.selectImportOption(URL_IMPORT)}>
URL
</Button>
{this.renderImportAttributes}
</div>
);
}
};
The React. js error "Objects are not valid as a React child" occurs when we try to directly render an object or an array in our JSX code. To solve the error, use the map() method to render arrays or access properties on the object in your JSX code.
React Child FunctionReact allows for you to specify a function as a child, which children is just a normal prop so it is equivalent to a render callback. Lets take a look at what this all looks like. Here we are using the LoadContent component, passing in a function, and then returning some content.
children is a special prop, automatically passed to every component, that can be used to render the content included between the opening and closing tags when invoking a component. These kinds of components are identified by the official documentation as “boxes”.
You can return children only without wrapping the children. Trick is to create a wrapper component then modify children into an array, which is required by React. Now you can simply just wrap anything else in this wrapper component. Now the elements inside the wrapper will render without having to wrap it in a DIV.
You need to call the function:
{this.renderImportAttributes()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With