HichiHachi
HichiHachi

Reputation: 491

How to get element properties in reactjs

I'm trying to get the height of the parent container element, to use as a height of an SVG background element.

Is there a way to get and pass this property?

I keep getting "TypeError: Cannot read property 'refs' of undefined"

const Services = ({ classes }) => {
    return (
        <div className={classes.Container} ref="container">//Element I want the height of
            <div className={classes.BGContainer}>
                <BGSVG width={'210'} height={this.refs.container.height} color={'blue'} />//Where I want to pass height to
            </div>
            <div className={classes.Services}>
                {services.map((e, i) => (
                    <ServiceItem
                        title={e.title}
                        icon={e.icon}
                        info={e.info}
                        inverted={i % 2 === 1 ? true : false}
                    />
                ))}
            </div>
        </div>
    );

Upvotes: 3

Views: 11128

Answers (3)

Stephen Collins
Stephen Collins

Reputation: 903

In a functional component, you need to use the React Hook called useRef like this:

const TextInputWithFocusButton = (props) => {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

you will see if you log out inputEl that a reference to the input element is logged. DOM element references allow you to access most properties of the particular DOM element referenced.

Upvotes: 1

Lazar Nikolic
Lazar Nikolic

Reputation: 4394

If your Services component is inside lets say ServicesWrapper Component, what you should do is put on it

`servicesWrapperContainerRef = React.createRef()`;

Then, on JSX of wrapper component place

`ref={this.servicesWrapperContainerRef}`

and then, pass that as a prop to the Services component like this const Services = ({ classes, servicesWrapperContainerRef }) and then you can use it to find out the parents height

`height={this.props.servicesWrapperContainerRef.current.clientHeight}`

Upvotes: 0

karfus
karfus

Reputation: 939

You haven't bound "this". Try height={() => this.refs.container.height}

Upvotes: 0

Related Questions