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>
);
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>
);
Share
Improve this question
edited Aug 14, 2019 at 16:16
HichiHachi
asked Aug 14, 2019 at 15:59
HichiHachiHichiHachi
4913 gold badges8 silver badges20 bronze badges
1
- if you console log this.refs.container inside this functional ponent what do you get? – Lazar Nikolic Commented Aug 14, 2019 at 16:03
3 Answers
Reset to default 1In a functional ponent, 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.
You haven't bound "this". Try height={() => this.refs.container.height}
If your Services ponent is inside lets say ServicesWrapper Component, what you should do is put on it
`servicesWrapperContainerRef = React.createRef()`;
Then, on JSX of wrapper ponent place
`ref={this.servicesWrapperContainerRef}`
and then, pass that as a prop to the Services ponent like this const Services = ({ classes, servicesWrapperContainerRef }) and then you can use it to find out the parents height
`height={this.props.servicesWrapperContainerRef.current.clientHeight}`