sumit
sumit

Reputation: 15464

check if element has scroll or not - reactjs

I have <table> enclosed in <div> . Whenever we have more data the <div> will have vertical scroll present in that case I want to make table width 100% and if vertical scroll is not there I want to make table width 98% .

render() {
  return (
    <div onScroll={this.handleScroll} className="scroll-property">
      <table className="react-listing-table table" width={this.setWidth()+'%'}>
      ...
  );
}

setWidth(){
  let dom = ReactDOM.findDOMNode(this).parentNode;
  let hasVerticalScrollbar = dom.scrollHeight > dom.clientHeight;

  if (hasVerticalScrollbar) {
    return 100;
  } else {
    return 98;
  }
}

The problem is that I am unable to find parent domNode i.e finding div from table and get the runtime error

typeError: Cannot read property 'parentNode' of null

Please guide me

Upvotes: 0

Views: 3961

Answers (1)

kingdaro
kingdaro

Reputation: 12018

When setWidth is called inside the render function, the DOM doesn't actually exist yet. This is something you want to do in componentDidMount instead, and probably componentDidUpdate as well, using a ref for the table.

tableRef = null

render() {
  return (
    <div onScroll={this.handleScroll} className="scroll-property">
      <table className="react-listing-table table" ref={el => this.tableRef = el}>
      ...
  );
}

componentDidMount() {
  this.tableRef.width = this.setWidth() + '%'
}

componentDidUpdate() {
  this.tableRef.width = this.setWidth() + '%'
}

Upvotes: 2

Related Questions