PositiveGuy PositiveGuy - 3 months ago 37
React JSX Question

Trouble Getting Component to Render in setTimeout

Not sure what I'm doing wrong but my component wrapped in setTimeout is not being rendered to the DOM:

const ContentMain = Component({
getInitialState() {
return {rendered: false};
},
componentDidMount() {
this.setState({rendered: true});
},
render(){
var company = this.props.company;

return (

<div id="ft-content">
{this.state.rendered && setTimeout(() => <Content company={company}/>,3000)}
</div>
)
}
})

Answer

I'd bet this isn't working because the render method needs all of its input to be consumed at the same time and it can't render other components in retrospect, there's a certain flow to React. I'd suggest to separate the timeout from render method anyway for logic's sake, and do it in componentDidMount like this:

const ContentMain = Component({
    getInitialState() {
        return {rendered: false};
    },
    componentDidMount() {
        setTimeout(() => {
            this.setState({rendered: true});
        }, 3000);
    },
    render(){
        if (!this.state.rendered) {
            return null;
        }

        var company = this.props.company;

        return (
            <div id="ft-content">
                <Content company={company}/>
            </div>
        )
    }
})

Changing the state triggers the render method.

On a side note - even if your original approach worked, you'd see the component flicker for 3 seconds every time it got rendered after the initial load. Guessing you wouldn't want that :)