Passing ref to child component to animate with GSAP - reactjs

I'm new to React and i am trying to integrate GSAP to animate a child component using refs. The process to try and animate worked fine before I seperated out the elements into their different components!
There are no error codes from React, but I do get the following console error:
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
I've looked into the forwardRef mentioned but not sure if it's right for what i'm trying to achieve.
/**
* Parent Component
*/
import React, { Component } from 'react';
import Spirit from './Spirit';
import { TweenMax, Power1 } from 'gsap';
class SpiritResults extends Component {
constructor(props) {
super(props);
this.multiElements = [];
}
componentDidMount() {
TweenMax.staggerFromTo(
this.multiElements,
0.5,
{ autoAlpha: 0 },
{ autoAlpha: 1, ease: Power1.easeInOut },
0.1
);
}
render() {
return (
<ul className="mm-results">
{this.props.spirits.map(({ id, title, featImg, link, slug, index }) => (
<Spirit
key={id}
slug={slug}
title={title}
featImg={featImg}
link={link}
ref={li => (this.multiElements[index] = li)}
/>
))}
</ul>
);
}
}
/**
* Child Component
*/
import React from 'react';
const Spirit = ({ slug, link, featImg, title, index }) => (
<li id={slug} className="mm-item" ref={index}>
<a href={link}>
<div className="inner">
<img src={featImg} alt={title} />
<h3>{title}</h3>
</div>
</a>
</li>
);
export default Spirit;
Any tips that can be given to get the animation to work would be appreciated. If there are any better ways of animating react with GSAP please let me know your thoughts.
Thanks

There are a few mistakes here.
ref is not a prop. You can't just pass it to a custom component and access it like props.ref
You're appending the wrong ref inside <li>, index is not a valid ref object
To pass down a ref to a custom component you need to use React.forwardRef and append the ref to your Child's <li>. Something like this
const Parent = () =>{
const ref = useRef(null)
return <Child ref={ref} title='hey i\'m a prop'/>
}
const Child = React.forwardRef((props, ref) =>(
<li ref={ref}>
{props.title}
</li>
))

Related

My button gives this error. Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? [duplicate]

I have the following (using Material UI)....
import React from "react";
import { NavLink } from "react-router-dom";
import Tabs from "#material-ui/core/Tabs";
import Tab from "#material-ui/core/Tab";
function LinkTab(link){
return <Tab component={NavLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
In the new versions this causes the following warning...
Warning: Function components cannot be given refs. Attempts to access
this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of ForwardRef.
in NavLink (created by ForwardRef)
I tried changing to...
function LinkTab(link){
// See https://material-ui.com/guides/composition/#caveat-with-refs
const MyLink = React.forwardRef((props, ref) => <NavLink {...props} ref={ref} />);
return <Tab component={MyLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
But I still get the warning. How do I resolve this issue?
Just give it as innerRef,
// Client.js
<Input innerRef={inputRef} />
Use it as ref.
// Input.js
const Input = ({ innerRef }) => {
return (
<div>
<input ref={innerRef} />
</div>
)
}
NavLink from react-router is a function component that is a specialized version of Link which exposes a innerRef prop for that purpose.
// required for react-router-dom < 6.0.0
// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678
const MyLink = React.forwardRef((props, ref) => <NavLink innerRef={ref} {...props} />);
You could've also searched our docs for react-router which leads you to https://mui.com/getting-started/faq/#how-do-i-use-react-router which links to https://mui.com/components/buttons/#third-party-routing-library. The last link provides a working example and also explains how this will likely change in react-router v6
You can use refs instead of ref. This only works as it avoids the special prop name ref.
<InputText
label="Phone Number"
name="phoneNumber"
refs={register({ required: true })}
error={errors.phoneNumber ? true : false}
icon={MailIcon}
/>
In our case, we were was passing an SVG component (Site's Logo) directly to NextJS's Link Component which was a bit customized and we were getting such error.
Header component where SVG was used and was "causing" the issue.
import Logo from '_public/logos/logo.svg'
import Link from '_components/link/Link'
const Header = () => (
<div className={s.headerLogo}>
<Link href={'/'}>
<Logo />
</Link>
</div>
)
Error Message on Console
Function components cannot be given refs. Attempts to access this ref will fail.
Did you mean to use React.forwardRef()?
Customized Link Component
import NextLink from 'next/link'
import { forwardRef } from 'react'
const Link = ({ href, shallow, replace, children, passHref, className }, ref) => {
return href ? (
<NextLink
href={href}
passHref={passHref}
scroll={false}
shallow={shallow}
replace={replace}
prefetch={false}
className={className}
>
{children}
</NextLink>
) : (
<div className={className}>{children}</div>
)
}
export default forwardRef(Link)
Now we made sure we were using forwardRef in the our customized Link Component but we still got that error.
In order to solve it, I changed the wrapper positioning of SVG element to this and :poof:
const Header = () => (
<Link href={'/'}>
<div className={s.headerLogo}>
<Logo />
</div>
</Link>
)
If you find that you cannot add a custom ref prop or forwardRef to a component, I have a trick to still get a ref object for your functional component.
Suppose you want to add ref to a custom functional component like:
const ref = useRef();
//throws error as Button is a functional component without ref prop
return <Button ref={ref}>Hi</Button>;
You can wrap it in a generic html element and set ref on that.
const ref = useRef();
// This ref works. To get button html element inside div, you can do
const buttonRef = ref.current && ref.current.children[0];
return (
<div ref={ref}>
<Button>Hi</Button>
</div>
);
Of course manage state accordingly and where you want to use the buttonRef object.
to fix this warning you should wrap your custom component with the forwardRef function as mentioned in this blog very nicely
const AppTextField =(props) {return(/*your component*/)}
change the above code to
const AppTextField = forwardRef((props,ref) {return(/*your component*/)}
const renderItem = ({ item, index }) => {
return (
<>
<Item
key={item.Id}
item={item}
index={index}
/>
</>
);
};
Use Fragment to solve React.forwardRef()? warning
If you're using functional components, then React.forwardRef is a really nice feature to know how to use for scenarios like this. If whoever ends up reading this is the more hands on type, I threw together a codesandbox for you to play around with. Sometimes it doesn't load the Styled-Components initially, so you may need to refresh the inline browser when the sandbox loads.
https://codesandbox.io/s/react-forwardref-example-15ql9t?file=/src/App.tsx
// MyAwesomeInput.tsx
import React from "react";
import { TextInput, TextInputProps } from "react-native";
import styled from "styled-components/native";
const Wrapper = styled.View`
width: 100%;
padding-bottom: 10px;
`;
const InputStyled = styled.TextInput`
width: 100%;
height: 50px;
border: 1px solid grey;
text-indent: 5px;
`;
// Created an interface to extend the TextInputProps, allowing access to all of its properties
// from the object that is created from Styled-Components.
//
// I also define the type that the forwarded ref will be.
interface AwesomeInputProps extends TextInputProps {
someProp?: boolean;
ref?: React.Ref<TextInput>;
}
// Created the functional component with the prop type created above.
//
// Notice the end of the line, where you wrap everything in the React.forwardRef().
// This makes it take one more parameter, called ref. I showed what it looks like
// if you are a fan of destructuring.
const MyAwesomeInput: React.FC<AwesomeInputProps> = React.forwardRef( // <-- This wraps the entire component, starting here.
({ someProp, ...props }, ref) => {
return (
<Wrapper>
<InputStyled {...props} ref={ref} />
</Wrapper>
);
}); // <-- And ending down here.
export default MyAwesomeInput;
Then on the calling screen, you'll create your ref variable and pass it into the ref field on the component.
// App.tsx
import React from "react";
import { StyleSheet, Text, TextInput, View } from "react-native";
import MyAwesomeInput from "./Components/MyAwesomeInput";
const App: React.FC = () => {
// Set some state fields for the inputs.
const [field1, setField1] = React.useState("");
const [field2, setField2] = React.useState("");
// Created the ref variable that we'll use down below.
const field2Ref = React.useRef<TextInput>(null);
return (
<View style={styles.app}>
<Text>React.forwardRef Example</Text>
<View>
<MyAwesomeInput
value={field1}
onChangeText={setField1}
placeholder="field 1"
// When you're done typing in this field, and you hit enter or click next on a phone,
// this makes it focus the Ref field.
onSubmitEditing={() => {
field2Ref.current.focus();
}}
/>
<MyAwesomeInput
// Pass the ref variable that's created above to the MyAwesomeInput field of choice.
// Everything should work if you have it setup right.
ref={field2Ref}
value={field2}
onChangeText={setField2}
placeholder="field 2"
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
app: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
});
export default App;
It's that simple! No matter where you place the MyAwesomeInput component, you'll be able to use a ref.
I just paste here skychavda solution, as it provide a ref to a child : so you can call child method or child ref from parent directly, without any warn.
source: https://github.com/reactjs/reactjs.org/issues/2120
/* Child.jsx */
import React from 'react'
class Child extends React.Component {
componentDidMount() {
const { childRef } = this.props;
childRef(this);
}
componentWillUnmount() {
const { childRef } = this.props;
childRef(undefined);
}
alertMessage() {
window.alert('called from parent component');
}
render() {
return <h1>Hello World!</h1>
}
}
export default Child;
/* Parent.jsx */
import React from 'react';
import Child from './Child';
class Parent extends React.Component {
onClick = () => {
this.child.alertMessage(); // do stuff
}
render() {
return (
<div>
<Child childRef={ref => (this.child = ref)} />
<button onClick={this.onClick}>Child.alertMessage()</button>
</div>
);
}
}

Is there a way of supplying a void function and supplying the innards of function when invoked in another place?

Basically what I'm trying to achieve is that, let's say that I have a function in a parent component in React. In a child component i want to do some calculation like lets say distance to nearest elements containing box. But I want to invoke this method via a button click or something in the parent. I have refs pointing to my child component and I can achieve this if I add the click to these children. But since I don't have acces to the parent method; how am I to achieve such behaviour?
Here's my child component:
import { FC, useRef } from 'react'
import styles from './Card.module.scss'
const Card: FC<CardProps> = ({ image, title, info }) => {
const cardRef = useRef<HTMLDivElement>(null)
const scroll = (offset: number) => {
if (cardRef.current) {
cardRef.current.scrollLeft += offset
}
}
return (
<div className={styles.card} ref={cardRef}>
<img src={image} alt={image.split('.')[0]} height={170} width={96} />
<div className={styles['card-info-container']}>
<h3>{title}</h3>
<p>{info}</p>
<img src="Chevron.svg" alt="Chevron" />
</div>
</div>
)
}
export default Card
interface CardProps {
image: string
title: string
info: string
}
and here is my parent component:
import Card from '../Card/Card'
import styles from './Campaigns.module.scss'
import { campaignData } from '../../mockdata/campaigndata'
const Campaigns = () => {
const scroll = (offset: number) => {}
return (
<section className={styles.campaigns}>
<h3></h3>
<div className={styles['cards-container']}>
{campaignData.map(({ image, title, description }, index) => (
<Card image={image} title={title} info={description} key={index} />
))}
</div>
</section>
)
}
export default Campaigns
I think I've found a solution but it's not really an elegant one in my opinion. Instead of agonizing over creating refs directly in the child I've opted to create an array of refs from the length of the content using React's createRef fucntion here's what I have in my parent component.
import Card from '../Card/Card'
import styles from './Campaigns.module.scss'
import { campaignData } from '../../mockdata/campaigndata'
import { createRef } from 'react'
const Campaigns = () => {
const refs = campaignData.map(() => createRef())
console.log(refs)
return (
<section className={styles.campaigns}>
<h3></h3>
<div className={styles['cards-container']}>
{campaignData.map(({ image, title, description }, index) => (
<Card
image={image}
title={title}
info={description}
key={index}
forwardRef={refs[index]}
/>
))}
</div>
</section>
)
}
export default Campaigns
Now I can reference every element as a seperate entity and without the hassle

CSSTransition nodeRef for component with direct children

I want to get rid of the warning on StrictMode for findDOMNode when using react-transition-group but I stumbled upon an issue.
My <Slide> component looks like this:
class Slide extends React.Component {
nodeRef = React.createRef();
render() {
return (
<CSSTransition
in={this.props.in}
timeout={ANIMATION_DURATION}
mountOnEnter={true}
unmountOnExit={true}
classNames={{
enter: "slideEnter",
enterActive: "slideEnterActive",
exit: "slideExit",
exitActive: "slideExitActive"
}}
nodeRef={this.nodeRef}
>
{this.props.children}
</CSSTransition>
);
}
}
It receives a Drawer element as children, the Drawer component looks like this:
class Drawer extends React.Component {
render() {
return (
<div className="drawer">
<button onClick={this.props.onClose}>close me</button>{" "}
<div>This is my drawer</div>
</div>
);
}
}
I cannot wrap the children element with a HTML tag (to attach a ref <div ref={this.nodeRef}>{this.props.children}</div> because it breaks the animation of the content. (I'm using this for children that are different drawers with position absolute)
I've also tried with cloneElement but it still doesn't work (with the code from below it behaves like this: 1. in no animation, 2. out no animation, 3. in animation works but I get the warning findDOMNode so it seems that nodeRef is sent as null, 4. out animation does not work.
const onlyChild = React.Children.only(this.props.children);
const childWithRef = React.cloneElement(onlyChild, {
ref: this.nodeRef;
});
Is there any solution for this situation? Thanks!
The problem is that nodeRef needs to point to a DOM Node, as the name suggests, in your case it points to an instance of the Drawer class. You have two options:
Pass the ref through another prop, e.g. forwardedRef, and in the Drawer class pass that prop to the root element:
React.cloneElement(onlyChild, {
forwardedRef: this.nodeRef,
})
<div ref={this.props.forwardedRef} className="drawer">
Convert Drawer to a function component and use React.forwardRef:
const Drawer = React.forwardRef((props, ref) => {
return (
<div ref={ref} className="drawer">
<button onClick={props.onClose}>close me</button>{" "}
<div>This is my drawer</div>
</div>
);
});

How to call functional component from another functionnal component in react js

I have to call a functional component from another functional component So how can I call child functional component from a functional component in react js.
import React from "react";
import TestFunctional from "./TestFucntional";
const TestListing = props => {
const { classes, theme } = props;
const handleClickTestOpen = () => {
return <TestFunctional />;
};
return (
<div>
<EditIcon
className={classes.icon}
onClick={handleClickTestOpen}
/>
</div>
);
};
export default TestListing;
I am trying to call or render TestFucntional component on EditIcon clicked but it is not called. So How can I call component?
Thanks.
You just use it in your jsx as a component as usual. You can see here
const ItemComponent = ({item}) => (
<li>{item.name}</li>)
const Component1 = ({list}) => (
<div>
MainComponent
<ul>
{list && list.map(item =><ItemComponent item={item} key={item.id}/>)}
</ul>
</div>)
const list = [{ id: 1, name: 'aaa'}, { id: 2, name: 'bbb'}]
ReactDOM.render(
<Component1 list={list}/>
, document.querySelector('.container')
);
From the above conversation, I guess you want conditional rendering, i.e. after any event you want to render the child component. To do so in the parent component, it should maintain a state. If you want to use functional parent component, you can use hooks. Or you can use some prop for the conditional rendering as well. Please provide a code snippet.
This is for reference: https://reactjs.org/docs/conditional-rendering.html

How do I avoid 'Function components cannot be given refs' when using react-router-dom?

I have the following (using Material UI)....
import React from "react";
import { NavLink } from "react-router-dom";
import Tabs from "#material-ui/core/Tabs";
import Tab from "#material-ui/core/Tab";
function LinkTab(link){
return <Tab component={NavLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
In the new versions this causes the following warning...
Warning: Function components cannot be given refs. Attempts to access
this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of ForwardRef.
in NavLink (created by ForwardRef)
I tried changing to...
function LinkTab(link){
// See https://material-ui.com/guides/composition/#caveat-with-refs
const MyLink = React.forwardRef((props, ref) => <NavLink {...props} ref={ref} />);
return <Tab component={MyLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
But I still get the warning. How do I resolve this issue?
Just give it as innerRef,
// Client.js
<Input innerRef={inputRef} />
Use it as ref.
// Input.js
const Input = ({ innerRef }) => {
return (
<div>
<input ref={innerRef} />
</div>
)
}
NavLink from react-router is a function component that is a specialized version of Link which exposes a innerRef prop for that purpose.
// required for react-router-dom < 6.0.0
// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678
const MyLink = React.forwardRef((props, ref) => <NavLink innerRef={ref} {...props} />);
You could've also searched our docs for react-router which leads you to https://mui.com/getting-started/faq/#how-do-i-use-react-router which links to https://mui.com/components/buttons/#third-party-routing-library. The last link provides a working example and also explains how this will likely change in react-router v6
You can use refs instead of ref. This only works as it avoids the special prop name ref.
<InputText
label="Phone Number"
name="phoneNumber"
refs={register({ required: true })}
error={errors.phoneNumber ? true : false}
icon={MailIcon}
/>
In our case, we were was passing an SVG component (Site's Logo) directly to NextJS's Link Component which was a bit customized and we were getting such error.
Header component where SVG was used and was "causing" the issue.
import Logo from '_public/logos/logo.svg'
import Link from '_components/link/Link'
const Header = () => (
<div className={s.headerLogo}>
<Link href={'/'}>
<Logo />
</Link>
</div>
)
Error Message on Console
Function components cannot be given refs. Attempts to access this ref will fail.
Did you mean to use React.forwardRef()?
Customized Link Component
import NextLink from 'next/link'
import { forwardRef } from 'react'
const Link = ({ href, shallow, replace, children, passHref, className }, ref) => {
return href ? (
<NextLink
href={href}
passHref={passHref}
scroll={false}
shallow={shallow}
replace={replace}
prefetch={false}
className={className}
>
{children}
</NextLink>
) : (
<div className={className}>{children}</div>
)
}
export default forwardRef(Link)
Now we made sure we were using forwardRef in the our customized Link Component but we still got that error.
In order to solve it, I changed the wrapper positioning of SVG element to this and :poof:
const Header = () => (
<Link href={'/'}>
<div className={s.headerLogo}>
<Logo />
</div>
</Link>
)
If you find that you cannot add a custom ref prop or forwardRef to a component, I have a trick to still get a ref object for your functional component.
Suppose you want to add ref to a custom functional component like:
const ref = useRef();
//throws error as Button is a functional component without ref prop
return <Button ref={ref}>Hi</Button>;
You can wrap it in a generic html element and set ref on that.
const ref = useRef();
// This ref works. To get button html element inside div, you can do
const buttonRef = ref.current && ref.current.children[0];
return (
<div ref={ref}>
<Button>Hi</Button>
</div>
);
Of course manage state accordingly and where you want to use the buttonRef object.
to fix this warning you should wrap your custom component with the forwardRef function as mentioned in this blog very nicely
const AppTextField =(props) {return(/*your component*/)}
change the above code to
const AppTextField = forwardRef((props,ref) {return(/*your component*/)}
const renderItem = ({ item, index }) => {
return (
<>
<Item
key={item.Id}
item={item}
index={index}
/>
</>
);
};
Use Fragment to solve React.forwardRef()? warning
If you're using functional components, then React.forwardRef is a really nice feature to know how to use for scenarios like this. If whoever ends up reading this is the more hands on type, I threw together a codesandbox for you to play around with. Sometimes it doesn't load the Styled-Components initially, so you may need to refresh the inline browser when the sandbox loads.
https://codesandbox.io/s/react-forwardref-example-15ql9t?file=/src/App.tsx
// MyAwesomeInput.tsx
import React from "react";
import { TextInput, TextInputProps } from "react-native";
import styled from "styled-components/native";
const Wrapper = styled.View`
width: 100%;
padding-bottom: 10px;
`;
const InputStyled = styled.TextInput`
width: 100%;
height: 50px;
border: 1px solid grey;
text-indent: 5px;
`;
// Created an interface to extend the TextInputProps, allowing access to all of its properties
// from the object that is created from Styled-Components.
//
// I also define the type that the forwarded ref will be.
interface AwesomeInputProps extends TextInputProps {
someProp?: boolean;
ref?: React.Ref<TextInput>;
}
// Created the functional component with the prop type created above.
//
// Notice the end of the line, where you wrap everything in the React.forwardRef().
// This makes it take one more parameter, called ref. I showed what it looks like
// if you are a fan of destructuring.
const MyAwesomeInput: React.FC<AwesomeInputProps> = React.forwardRef( // <-- This wraps the entire component, starting here.
({ someProp, ...props }, ref) => {
return (
<Wrapper>
<InputStyled {...props} ref={ref} />
</Wrapper>
);
}); // <-- And ending down here.
export default MyAwesomeInput;
Then on the calling screen, you'll create your ref variable and pass it into the ref field on the component.
// App.tsx
import React from "react";
import { StyleSheet, Text, TextInput, View } from "react-native";
import MyAwesomeInput from "./Components/MyAwesomeInput";
const App: React.FC = () => {
// Set some state fields for the inputs.
const [field1, setField1] = React.useState("");
const [field2, setField2] = React.useState("");
// Created the ref variable that we'll use down below.
const field2Ref = React.useRef<TextInput>(null);
return (
<View style={styles.app}>
<Text>React.forwardRef Example</Text>
<View>
<MyAwesomeInput
value={field1}
onChangeText={setField1}
placeholder="field 1"
// When you're done typing in this field, and you hit enter or click next on a phone,
// this makes it focus the Ref field.
onSubmitEditing={() => {
field2Ref.current.focus();
}}
/>
<MyAwesomeInput
// Pass the ref variable that's created above to the MyAwesomeInput field of choice.
// Everything should work if you have it setup right.
ref={field2Ref}
value={field2}
onChangeText={setField2}
placeholder="field 2"
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
app: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
});
export default App;
It's that simple! No matter where you place the MyAwesomeInput component, you'll be able to use a ref.
I just paste here skychavda solution, as it provide a ref to a child : so you can call child method or child ref from parent directly, without any warn.
source: https://github.com/reactjs/reactjs.org/issues/2120
/* Child.jsx */
import React from 'react'
class Child extends React.Component {
componentDidMount() {
const { childRef } = this.props;
childRef(this);
}
componentWillUnmount() {
const { childRef } = this.props;
childRef(undefined);
}
alertMessage() {
window.alert('called from parent component');
}
render() {
return <h1>Hello World!</h1>
}
}
export default Child;
/* Parent.jsx */
import React from 'react';
import Child from './Child';
class Parent extends React.Component {
onClick = () => {
this.child.alertMessage(); // do stuff
}
render() {
return (
<div>
<Child childRef={ref => (this.child = ref)} />
<button onClick={this.onClick}>Child.alertMessage()</button>
</div>
);
}
}

Resources