4
votes

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>

        );
    }
};
2
Ah i found I miss brackets in function call in renderMartin

2 Answers

13
votes

You need to call the function: {this.renderImportAttributes()}

3
votes
 {this.renderImportAttributes}

Here you are just referring to the function declaration, you have not invoked the function.

You can execute it before the return, like:

render() {
    let elems = this.renderImportAttributes();

    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>
            {elems}
        </div>

    );
}