0

I have a Navigation component here that toggles a class onClick

import React from "react";

//COMPONENTS

import Navlinks from './Navlinks';

class Navigation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {addClass: false}
  }
  toggle() {
    setTimeout(() => {
      this.setState({addClass: !this.state.addClass});
    }, 200);
  }
  render() {
    let navClass = ["nav"];
    if(this.state.addClass) {
      navClass.push('open');
    }
    return(
        <div className={navClass.join(' ')} onClick={this.toggle.bind(this)}>
          <div className="icon"></div>
          <Navlinks onClick={this.props.onClick}/>
        </div>       
    );
  }
}
export default Navigation;

Is there a way that I can somehow disable the onClick event when the device viewport is larger than a certain size?

DesignAaron
  • 131
  • 7
  • An easy way would be to [check the viewport size](https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions) in the onClick handler and just return if the viewport is larger than the specified size. – cbr Jan 09 '21 at 18:46

1 Answers1

1

Would this help: I am using window.innerWidth to check the width of the viewport and setting onClick accordingly on condition.

import React from "react";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { addClass: false, vw: window.innerWidth };
  }
  toggle() {
    console.log("Toggle Method");
  }

  notToggle() {
    console.log("Not Toggling");
  }
  render() {
    return (
      <div
        onClick={
          this.vw > 800 ? this.toggle.bind(this) : this.notToggle.bind(this)
        }
      >
        <div className="icon">Hellow Hellow</div>
      </div>
    );
  }
}

export default App;
Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35