Can't access child function from parent function with React Hooks - reactjs

I need to call a function in a child component from a parent component with React Hooks.
I was trying to adapt this question to my use case React 16: Call children's function from parent when using hooks and functional component
but I keep getting the error
TypeError: childRef.childFunction is not a function
My parent component is like this:
import React, { useRef, useEffect } from 'react';
import Child from './child'
function Parent() {
const parentRef = useRef()
const childRef = useRef()
const callChildFunction = () => {
childRef.current(childRef.childFunction())
}
useEffect(() => {
if (parentRef && childRef) {
callChildFunction();
}
}, [parentRef, childRef])
return (
<div ref={parentRef} className="parentContainer">
PARENT
<Child ref={childRef}/>
</div>
);
}
export default Parent;
My child component is like this:
import React, { forwardRef, useImperativeHandle } from 'react';
const Child = forwardRef(({ref}) => {
useImperativeHandle(ref, () => ({
childFunction() {
console.log("CHILD FUNCTION")
}
}));
return (
<div className="childContainer">
CHILD
</div>
);
})
export default Child;
What am I doing wrong?

I think this is your problem
childRef.current(childRef.childFunction())
childRef.current isn't a function. Also childRef.childFunction() is run first, which also isn't a function.
childRef.current.childFunction should be a function, try childRef.current.childFunction() instead of childRef.current(childRef.childFunction())
From the docs on useImperativeHandle check out the usage of inputRef.current.focus():
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
In this example, a parent component that renders <FancyInput ref={inputRef} /> would be able to call inputRef.current.focus().
Edit based on comment for future visitors:
const Child = forwardRef(({ref}) => {
should be
const child = forwardRef(({}, ref) => {

Related

Pass state between Parent and Child components in React/Typescript

I am a little confused as to how to update state between parent and child components. I know state needs to be lifted up which is why I have added it to the parent component. So I want to update the boolean value in the child component(can this be done?). I have tried as below but get the error: Cannot invoke an object which is possibly 'undefined'. This expression is not callable.Type 'Boolean' has no call signatures.
Stackblitz example: https://stackblitz.com/edit/react-ts-hzssfh?file=Child.tsx
Parent
import React from 'react';
import Child from '../components/Child';
const Parent: React.FunctionComponent = () => {
const [visible, setVisible] = React.useState<boolean>(false);
const toggle = () => {
setVisible(!visible);
};
return (
<button onClick={toggle}>toggle</button>
<Child visible={visible} />
)
};
export default Parent;
Child
import React from 'react';
interface Icomments {
visible?: boolean;
}
const Child: React.FunctionComponent<Icomments> = (props: Icomments) => {
const handleClick = () => {
props.visible(false);
};
return (
<button onClick={handleClick}>Hide</button>
)
}
export default Child;
The child needs the function that sets the state - not the state value. So you need to pass down to the Child the setVisible function as a prop.
<Child setVisible={setVisible} />
const Child = ({ setVisible }) => (
<button onClick={() => { setVisible(false); }}>Hide</button>
);

Trigger child function from parent component using react hooks

I have some action buttons in parent components. On click of one of such buttons, I would like to trigger a function in the child component. Currently, I am trying to implement it using useRef hook. But the solution seems tedious and also gives me warning:
My current code looks like:
import React, {useContext, useEffect, useState, useRef} from 'react';
const ParentComponent = ({...props})=> {
const myRef = useRef();
const onClickFunction = () => {
if(myRef.current) {
myRef.current.childFunction();
}
}
return (
<ChildComponent ref = {myRef}/>
);
}
Child component
const ChildComponent = (({}, ref,{ actionButtons, ...props}) => {
const [childDataApi, setChildDataApi] = useState(null);
const childFunction = () => {
//update childDataApi and pass it to parent
console.log("inside refreshEntireGrid");
}
});
Firstly, is there a better solution then trying to trigger childFunction from parent ? For this I am following this solution:
Can't access child function from parent function with React Hooks
I tried adding forward ref but that threw error as well.
I also found out that lifting the state up could be another solution as well. But I am not able to understand how to apply that solution in my case. Can someone please help me with this.
The warning says you were using forwardRef so with your snippet const ChildComponent = (({}, ref, { actionButtons, ...props }) => { .... } I'll assume this is a typo in your question and you were actually doing const ChildComponent = React.forwardRef(({}, ref,{ actionButtons, ...props }) => { .... }).
The issue here, and the warning message points this out, is that you are passing a third argument to forwardRef when it only consumes two. It seems you destructure nothing from the first props argument. From what I can tell you should replace the first argument with the third where it looks like you are doing some props destructuring.
const ChildComponent = React.forwardRef(({ actionButtons, ...props }, ref) => { .... }
From here you should implement the useImperativeHandle hook to expose out the function from the child.
const ChildComponent = React.forwardRef(({ actionButtons, ...props }, ref) => {
const [childDataApi, setChildDataApi] = useState(null);
const childFunction = () => {
// update childDataApi and pass it to parent
console.log("inside refreshEntireGrid");
}
useImperativeHandle(ref, () => ({
childFunction
}));
...
return ( ... );
});
In the parent component:
const ParentComponent = (props) => {
const myRef = useRef();
const onClickFunction = () => {
myRef.current?.childFunction();
}
return (
<ChildComponent ref={myRef}/>
);
}
Something else you can try is to pass a prop to the child to indicate that the button has been clicked and use useEffect in the child component to do something when that value changes.
const Child = props => {
useEffect(() => TriggeredFunc(), [props.buttonClicked]);
const TriggeredFunc = () => {
...
}
return '...';
}
const Parent = () => {
const [buttonClicked, setButtonClicked] = useState(0);
const onClick = e => {
setButtonClicked(buttonClicked++);
}
return <>
<button onClick={onClick}>My Button</button>
<Child buttonClicked={buttonClicked} />;
</>
}

How to pass data from child to parent component using react hooks

I have a Parent component and couple of child components. I need to disable or enable the button in the parent based on the ErrorComponent. If there is an error then I disable the button or else I enable it. I believe we can pass callbacks from the child to parent and let the parent know and update the button property. I need to know how to do the same using react hooks? I tried few examples but in vain. There is no event on error component. If there is an error (props.errorMessage) then I need to pass some data to parent so that I can disable the button. Any help is highly appreciated
export const Parent: React.FC<Props> = (props) => {
....
const createContent = (): JSX.Element => {
return (
{<ErrorPanel message={props.errorMessage}/>}
<AnotherComponent/>
);
}
return (
<Button onClick={onSubmit} disabled={}>My Button</Button>
{createContent()}
);
};
export const ErrorPanel: React.FC<Props> = (props) => {
if (props.message) {
return (
<div>{props.message}</div>
);
}
return null;
};
I'd use useEffect hook in this case, to set the disabled state depending on the message props. You can see the whole working app here: codesandbox
ErrorPanel component will look like this:
import React, { useEffect } from "react";
interface IPropTypes {
setDisabled(disabled:boolean): void;
message?: string;
}
const ErrorPanel = ({ setDisabled, message }: IPropTypes) => {
useEffect(() => {
if (message) {
setDisabled(true);
} else {
setDisabled(false);
}
}, [message, setDisabled]);
if (message) {
return <div>Error: {message}</div>;
}
return null;
};
export default ErrorPanel;
So depending on the message prop, whenever it 'exists', I set the disabled prop to true by manipulating the setDisabled function passed by the prop.
And to make this work, Parent component looks like this:
import React, { MouseEvent, useState } from "react";
import ErrorPanel from "./ErrorPanel";
interface IPropTypes {
errorMessage?: string;
}
const Parent = ({ errorMessage }: IPropTypes) => {
const [disabled, setDisabled] = useState(false);
const createContent = () => {
return <ErrorPanel setDisabled={setDisabled} message={errorMessage} />;
};
const handleSubmit = (e: MouseEvent) => {
e.preventDefault();
alert("Submit");
};
return (
<>
<button onClick={handleSubmit} disabled={disabled}>
My Button
</button>
<br />
<br />
{createContent()}
</>
);
};
export default Parent;

Any better way to pass data from a child component to a function in a parent component without using bind()?

I'm using React.Context to pass a function down to child component which is inside another component. See figure down below.
I'm quite not comfortable using .bind() in order to pass the name variable to the function in the parent component.
Is there a better way to pass data from a child component to a function in a parent component without using .bind()?
See my code below:
import React, { Component, createContext } from 'react'
const AppContext = createContext()
class ComponentOne extends Component {
const handleClick = (name)=> {
alert(`Hello ${name}`)
}
render(){
return(
<AppContext.Provider
value={{
handleClick: this.handleClick
}}>
<p>Hello from ComponentOne</p>
</AppContext.Provider>
)
}
}
const ComponentThree = props=> {
const name = "lomse"
return(
<AppContext.Consumer>
(context=>(
<button onClick={context.handleClick.bind(null, name)}>Click me!</button>
))
</AppContext.Consumer>
)
}
You can always do:
const ComponentThree = props=> {
const name = "lomse"
return(
<AppContext.Consumer>
(context=> {
const handleClick = () => context.handleClick(name)
return <button onClick={handleClick}>Click me!</button>
})
</AppContext.Consumer>
)
}
What you're doing is about binding arguments so when a function is called later it will be called with those arguments. It has nothing to do with React Context.
and onClick needs to be a function, that will be called - well - on click.
Or you could do:
const handleClick = (name) => () => {
alert(`Hello ${name}`)
}
and then:
const ComponentThree = props=> {
const name = "lomse"
return(
<AppContext.Consumer>
(context=> (
<button onClick={context.handleClick(name)}>Click me!</button>
))
</AppContext.Consumer>
)
}

Can a React portal be used in a Stateless Functional Component (SFC)?

I have used ReactDOM.createPortal inside the render method of a stateful component like so:
class MyComponent extends Component {
...
render() {
return (
<Wrapper>
{ReactDOM.createPortal(<FOO />, 'dom-location')}
</Wrapper>
)
}
}
... but can it also be used by a stateless (functional) component?
Will chime in with an option where you dont want to manually update your index.html and add extra markup, this snippet will dynamically create a div for you, then insert the children.
export const Portal = ({ children, className = 'root-portal', el = 'div' }) => {
const [container] = React.useState(() => {
// This will be executed only on the initial render
// https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
return document.createElement(el);
});
React.useEffect(() => {
container.classList.add(className)
document.body.appendChild(container)
return () => {
document.body.removeChild(container)
}
}, [])
return ReactDOM.createPortal(children, container)
}
It can be done like this for a fixed component:
const MyComponent = () => ReactDOM.createPortal(<FOO/>, 'dom-location')
or, to make the function more flexible, by passing a component prop:
const MyComponent = ({ component }) => ReactDOM.createPortal(component, 'dom-location')
can it also be used by a stateless (functional) component
?
yes.
const Modal = (props) => {
const modalRoot = document.getElementById('myEle');
return ReactDOM.createPortal(props.children, modalRoot,);
}
Inside render :
render() {
const modal = this.state.showModal ? (
<Modal>
<Hello/>
</Modal>
) : null;
return (
<div>
<div id="myEle">
</div>
</div>
);
}
Working codesandbox#demo
TSX version based on #Samuel's answer (React 17, TS 4.1):
// portal.tsx
import * as React from 'react'
import * as ReactDOM from 'react-dom'
interface IProps {
className? : string
el? : string
children : React.ReactNode
}
/**
* React portal based on https://stackoverflow.com/a/59154364
* #param children Child elements
* #param className CSS classname
* #param el HTML element to create. default: div
*/
const Portal : React.FC<IProps> = ( { children, className, el = 'div' } : IProps ) => {
const [container] = React.useState(document.createElement(el))
if ( className )
container.classList.add(className)
React.useEffect(() => {
document.body.appendChild(container)
return () => {
document.body.removeChild(container)
}
}, [])
return ReactDOM.createPortal(children, container)
}
export default Portal
IMPORTANT useRef/useState to prevent bugs
It's important that you use useState or useRef to store the element you created via document.createElement because otherwise it gets recreated on every re-render
//This div with id of "overlay-portal" needs to be added to your index.html or for next.js _document.tsx
const modalRoot = document.getElementById("overlay-portal")!;
//we use useRef here to only initialize el once and not recreate it on every rerender, which would cause bugs
const el = useRef(document.createElement("div"));
useEffect(() => {
modalRoot.appendChild(el.current);
return () => {
modalRoot.removeChild(el.current);
};
}, []);
return ReactDOM.createPortal(
<div
onClick={onOutSideClick}
ref={overlayRef}
className={classes.overlay}
>
<div ref={imageRowRef} className={classes.fullScreenImageRow}>
{renderImages()}
</div>
<button onClick={onClose} className={classes.closeButton}>
<Image width={25} height={25} src="/app/close-white.svg" />
</button>
</div>,
el.current
);
Yes, according to docs the main requirements are:
The first argument (child) is any renderable React child, such as an element, string, or fragment. The second argument (container) is a DOM element.
In case of stateless component you can pass element via props and render it via portal.
Hope it will helps.
Portal with SSR (NextJS)
If you are trying to use any of the above with SSR (for example NextJS) you may run into difficulty.
The following should get you what you need. This methods allows for passing in an id/selector to use for the portal which can be helpful in some cases, otherwise it creates a default using __ROOT_PORTAL__.
If it can't find the selector then it will create and attach a div.
NOTE: you could also statically add a div and specify a known id in pages/_document.tsx (or .jsx) if again using NextJS. Pass in that id and it will attempt to find and use it.
import { PropsWithChildren, useEffect, useState, useRef } from 'react';
import { createPortal } from 'react-dom';
export interface IPortal {
selector?: string;
}
const Portal = (props: PropsWithChildren<IPortal>) => {
props = {
selector: '__ROOT_PORTAL__',
...props
};
const { selector, children } = props;
const ref = useRef<Element>()
const [mounted, setMounted] = useState(false);
const selectorPrefixed = '#' + selector.replace(/^#/, '');
useEffect(() => {
ref.current = document.querySelector(selectorPrefixed);
if (!ref.current) {
const div = document.createElement('div');
div.setAttribute('id', selector);
document.body.appendChild(div);
ref.current = div;
}
setMounted(true);
}, [selector]);
return mounted ? createPortal(children, ref.current) : null;
};
export default Portal;
Usage
The below is a quickie example of using the portal. It does NOT take into account position etc. Just something simple to show you usage. Sky is limit from there :)
import React, { useState, CSSProperties } from 'react';
import Portal from './path/to/portal'; // Path to above
const modalStyle: CSSProperties = {
padding: '3rem',
backgroundColor: '#eee',
margin: '0 auto',
width: 400
};
const Home = () => {
const [visible, setVisible] = useState(false);
return (
<>
<p>Hello World <a href="#" onClick={() => setVisible(true)}>Show Modal</a></p>
<Portal>
{visible ? <div style={modalStyle}>Hello Modal! <a href="#" onClick={() => setVisible(false)}>Close</a></div> : null}
</Portal>
</>
);
};
export default Home;
const X = ({ children }) => ReactDOM.createPortal(children, 'dom-location')
Sharing my solution:
// PortalWrapperModal.js
import React, { useRef, useEffect } from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
const PortalWrapperModal = ({
children,
onHide,
backdrop = 'static',
focus = true,
keyboard = false,
}) => {
const portalRef = useRef(null);
const handleClose = (e) => {
if (e) e.preventDefault();
if (portalRef.current) $(portalRef.current).modal('hide');
};
useEffect(() => {
if (portalRef.current) {
$(portalRef.current).modal({ backdrop, focus, keyboard });
$(portalRef.current).modal('show');
$(portalRef.current).on('hidden.bs.modal', onHide);
}
}, [onHide, backdrop, focus, keyboard]);
return ReactDOM.createPortal(
<>{children(portalRef, handleClose)}</>,
document.getElementById('modal-root')
);
};
export { PortalWrapperModal };

Resources