简体   繁体   中英

React Server Side Rendering - addEventListener

I have a server side rendering react app (because I need Facebook Seo as well).

A part of my app requires to get window.innerWidth.

I have been searching for a long time, most of them says you cannot find window on server side, so you need to do rendering on client side as well .

I'm not sure how things work, I have componentdidmount but my windowWidth is forever 0.

After server rendering, our bundle.js will kick in and window on client side will work right? How come it's still 0?

state = {
      windowWidth: 0
}
    handleResize(){
        this.setState({windowWidth: window.innerWidth});
    }

    componentDidMount () {
        window.addEventListener('resize', this.handleResize);
     }

    componentWillUnmount () {
     window.removeEventListener('resize', this.handleResize);

    }

render() {
return (<div>{this.state.windowWidth}</div>)
}

The problem is that you attaching a function to set the new width to a "resize" listener which means only when you resize the screen the new width will added to state. You need to set the width inside componentDidMount and then you will have it width right on mount.

sandbox

CODE:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      windowWidth: 0
    };
  }

  handleResize = () => {
    this.setState({ windowWidth: window.innerWidth });
  };

  componentDidMount() {
    this.setState({ windowWidth: window.innerWidth });
    window.addEventListener("resize", this.handleResize);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.handleResize);
  }

  render() {
    return (
      <div>{this.state.windowWidth && <p>{this.state.windowWidth}</p>}</div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM