jsx-eslint/eslint-plugin-react

Rule Proposal: Check for global references inside `render`

Open

#246 aperta il 13 ott 2015

Vedi su GitHub
 (4 commenti) (0 reazioni) (0 assegnatari)JavaScript (2797 fork)batch import
acceptedhelp wantednew rule

Metriche repository

Star
 (8630 star)
Metriche merge PR
 (Nessuna PR mergiata in 30 g)

Descrizione

When using React for server rendering, it can be problematic when a component relies on window or document or other globals inside of render. It will cause checksum issues when you get to the client. Instead of checking whether you are on the client within render, it's better to use the componentDidMount lifecycle event to set a state which is used in render instead.

Problematic:

class Foo extends React.Component {
    render() {
        if (typeof window === 'undefined') {
            return null;
        }
        return <Bar />;
    }
}

Better:

class Foo extends React.Component {
    constructor() {
        this.state = {showBar: false};
    }
    componentDidMount() {
        this.setState({showBar: true});
    }
    render() {
        if (!this.state.showBar) {
            return null;
        }
        return <Bar />;
    }
}

Guida contributor