14

I have a select field, but I can't get width of this select using React Ref.

enter image description here

this.selectRef.current is an object, but it seems there is no way to get width of the element

     <Select
        fullWidth
        ref={this.selectRef}
        onChange={event => {
          this.setState({
            value: event.target.value
          });
        }}
        value={this.state.value}
      >
        <MenuItem value={0}>Zero</MenuItem>
        <MenuItem value={1}>One</MenuItem>
        <MenuItem value={2}>Two</MenuItem>
        <MenuItem value={3}>Three</MenuItem>
        <MenuItem value={4}>Four</MenuItem>
      </Select>

Sandbox example https://codesandbox.io/embed/hungry-galileo-eydfw

1
  • Hi fetchenko, please try my solution below and let me know if that helps :) Commented Aug 2, 2019 at 8:14

1 Answer 1

19

Just wrap the Select component in a div and give that div the ref.

Additionally, try to use state to record the width and define that ref-width reading logic outside of the render. Put it in componentDidMount() instead, that way we've ensured that the element has rendered to the screen and we don't need to check if ref.current is truthy.

Also you can use.clientWidth instead of .offsetWidth so that you get the actual element width, not including borders.

See working sandbox:

import React, { Component } from "react";
import { Select, MenuItem } from "@material-ui/core";

class MySelect extends Component {
  constructor(props) {
    super(props);

    this.state = {
      value: 0,
      open: false,
      width: null
    };

    this.selectRef = React.createRef();
  }

  componentDidMount() {
    const width = this.selectRef.current.clientWidth;
    this.setState(
      {
        width: width
      },
      () => console.log(this.state.width)
    );
  }

  render() {
    return (
      <div ref={this.selectRef}>
        <Select
          fullWidth
          ref={this.selectRef}
          onChange={event => {
            this.setState({
              value: event.target.value
            });
          }}
          value={this.state.value}
        >
          <MenuItem value={0}>Zero</MenuItem>
          <MenuItem value={1}>One</MenuItem>
          <MenuItem value={2}>Two</MenuItem>
          <MenuItem value={3}>Three</MenuItem>
          <MenuItem value={4}>Four</MenuItem>
        </Select>
      </div>
    );
  }
}

export default MySelect;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.