Categories
React Tips

React Tips — Event Handlers, componentDidUpdate, and Height of an Element

Spread the love

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Get Height of an Element

We can get the height of an element by assign a ref to an element and then use the clientHeight property to get the height of it.

For instance, we can write:

import React, {Component} from 'react'

class DivSize extends Component {

  constructor(props) {
    super(props)

    this.state = {
      height: 0
    }
  }

  componentDidMount() {
    const height = this.divElement.clientHeight;
    this.setState({ height });
  }

  render() {
    return (
      <div
        className="test"
        ref={(divElement) => { this.divElement = divElement }}
      >
        Size: <b>{this.state.height}px</b>
      </div>
    )
  }
}

We assigned a ref to the div element by writing:

ref={(divElement) => { this.divElement = divElement }}

Then in the componentDidMount hook, we can the div’s height with the clientHeight property.

Then we call setState to set the height state.

With function components, we can do the same thing.

For instance, we can write:

import React, { useState, useEffect, useRef } from 'react'

export default () => {
  const [height, setHeight] = useState(0)
  const ref = useRef(null)

  useEffect(() => {
    setHeight(ref.current.clientHeight)
  }, [])

  return (
    <div ref={ref}>
      {height}
    </div>
  )
}

We create a ref and assign it to the div.

The ref is created with the useRef hook.

We also call useState to create a state for the height and a function to set it.

Then in the useEffect callback, we can call the setHeight function with the ref.current.clientHeight to set the value of height state to the div’s height.

Then we display the height in the div.

Using this.props.children for Displaying Child Components

We can use this.props.children to display child components.

For instance, we can write:

class Parent extends React.Component {
  render() {
    return <div>
      <div>Children ({this.props.children.length}):</div>
      {this.props.children}
    </div>;
  }
}

class App extends React.Component {
  render() {
    return <div>
      <div>first example</div>
      <Parent>
        <div>1</div>
        <div>2</div>
        <div>3</div>
      </Parent>
      <div>second example</div>
      <Parent>
        <div>A</div>
        <div>B</div>
      </Parent>
    </div>;
  }
}

We created a Parent component that rendered the children prop.

Then in the App component, we used the Parent component.

And then we pass in the divs that we want to display as the children of Parent .

And they’ll be displayed.

this.props.children is an array, so we can display the length of the children prop.

Call Multiple Functions onClick in React

We can call multiple functions in our click handler.

For instance, we can write:

class App extends React.Component {
   onClick(event) {
      func1();
      func2();
   }
   render() {
      return (
         <button onClick={this.onClick}>click me</button>
      );
   }
}

We have the onClick method that calls multiple functions.

If we want to do that inline, we can write:

class App extends React.Component {
   render() {
      return (
         <button onClick={() => { func1(); func2(); }}>click me</button>
      );
   }
}

Uses for the React “componentDidUpdate” Method

We can use the componentDidUpdate method to watch for changes in our state values and then run code when they change.

For instance, we can write:

class Form extends React.Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      firstName: "",
      lastName: "",
      age: ""
    };
    this.changeFirstName = this.changeFirstName.bind(this);
    this.changeLastName = this.changeLastName.bind(this);
    this.changeAge = this.changeAge.bind(this);
  }

  componentDidUpdate() {
    this.autoSave();
  }

  changeFirstName(e){
    this.setState({ firstName: e.target.value });
  }

  changeAge(e){
    this.setState({ age: e.target.value });
  }

  changeLastName(e) {
    this.setState({ lastName: e.target.value });
  }

  autoSave() {
    const { firstName, lastName, age } = this.state;
    post('/autosave', {
      firstName,
      lastName,
      age
    });
  }

  render() {
    const { firstName, lastName, age } = this.state;
    return (
      <form>
        <input type="text" value={firstName} onChange={this.changeFirstName} />
        <input type="text" value={lastName} onChange={this.changeLastName} />
        <input type="text" value={age} onChange={this.changeAge} />
      </form>
    );
  }
}

We have 3 inputs with 3 change handlers to update each of their inputted values as the new state values.

Once that happens, the componentDidUpdate will run and the POST request will be made.

It’ll run after the DOM is updated and the update queue is emptied.

Conclusion

componentDidUpdate is useful for running updates when the state updates.

We can get the height of an element by assigning a ref and using the clientHeight property on it.

We can call whatever we want in our event handlers.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *