React DOM change component on window resize

Kim B :

I need to change the logo when window width small than 768 but can't realize it. Must be responsive on window width changes. what is wrong with my code? thank you!

export default class Header extends Component {
    constructor(props) {
        super(props);
        this.state = {
            winWidth: 0
        };
        this.getWindowSize = this.getWindowSize.bind(this);
    }

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

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

      getWindowSize() {
        this.setState({ winWidth: window.innerWidth});
      }

    changeLogo(logo){
        if(this.state.winWidth < 768){
            logo = './images/small.png';

        }
        logo = './images/regular.png';   
    }


    render() {
        const {logo} = this.props;
        return (
               <div className="Header">
                 <img src={ this.changeLogo(logo) } alt="logo"/>
            </div> 
        )
    }
}
Nikolai Kiselev :

Try to use CSS instead of JS to show different images based on the screen width.

<Header class="Header">
    <img src="./images/small.png" className="small-screen-logo" alt="logo"/>
    <img src="./images/regular.png" className="large-screen-logo" alt="logo"/>
</Header> 

Display a small screen logo, if the screen size is more than 768px display the bigger screen logo

.small-screen-logo {
    display: block;
}

.large-screen-logo {
    display: none;
}


@media (min-width: 768px) {
    .small-screen-logo {
        display: none;
    }

    .large-screen-logo {
        display: block;
    }
}

If you use bootstrap you can achieve it with bootstrap classes:

<Header class="Header">
    <img src="./images/small.png" className="d-block d-md-none" alt="logo"/>
    <img src="./images/regular.png" className="d-none d-md-block" alt="logo"/>
</Header> 

Suggested reading https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Media_queries

In case you want to use JS you can add a method logo instead of changeLogo(logo).

logo() {
    return './images/' + (this.state.winWidth < 768 ? 'small.png' : 'regular.png') + '.png';
}

Then use it in render as following:

<img src={logo} alt="logo"/>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33280&siteId=1