Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass ref with function component?

-I am using function component. -for now I am using 3 components here, from that One is parent component and another 2 are child components. -I need to access one child component methods or state to another child methods. I already done with class components with CreateRef but for now I need to use with function components but I am getting Null inside 'ref.current'.

export function SideBySideList(props) {
    const ref = React.createRef();

	//this is call inside ListPage after sucess
    function updateRightList(id) {
        ref.current.state.actualSearchedModel.Id = id
        ref.current.fetchDataAndUpdate();
    }
    function itemClicked(id) {
        updateRightList(id);
    }
    return (
        <>
            <div className="col-12 no-padding">
                <div className={props.leftListLayoutClass}>
                    <ListPage
					    updateRightList={updateRightList}
					/>
                </div>
                <div className={props.rightListLayoutClass}>
                    <ListPage
                        ref={ref}
                    />
                </div>
            </div>
        <>
    );
}
like image 650
Devangsinh Rathod Avatar asked Mar 03 '23 10:03

Devangsinh Rathod


2 Answers

According to the official documentation:

You may not use the ref attribute on function components because they don’t have instances

So if your ListPage is functional component, you have to convert it to the class component. Or your ref must refer to the DOM element inside of ListPage.

function ListPage ({ref}) {
  return <div ref={ref}>Hello!</div>
}

UPDATED:

function ParentComponent () {
  const [state, setState] = React.useState(null);
  
  const onChildMount = React.useCallback((dataFromChild) => {
    setState(dataFromChild);
  });
  
  return (
    <div>
      <pre>{JSON.stringify(state, null, 2)}</pre>
      <ChildComponent onMount={onChildMount} />
    </div>
  )
}

function ChildComponent (props) {
  const thisShouldBePassedToTheParent = "from child with love";
  
  React.useEffect(() => {
    props.onMount(thisShouldBePassedToTheParent);
  }, []);
  
  return (
    <div>child component</div>
  )
}

ReactDOM.render(<ParentComponent />, document.querySelector("#root"));
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
<div id="root"></div>
like image 64
Ivan Burnaev Avatar answered Mar 11 '23 02:03

Ivan Burnaev


With functional components you can use refs like this:

// Import our hooks
import React, { useRef, useEffect } from 'react';

// create our ref
const myInput = useRef();

// This is equivalent to our componentDidMount, this will focus
useEffect(() => myInput.current && myInput.current.focus());

// Parse our ref to our textField
<Textfield inputRef={myInput} />

Here you can read docs https://reactjs.org/docs/hooks-reference.html#useref

Also you may use refs like this directly:

<TextField inputRef={input => input && input.focus()} />

You can read full Article here: https://medium.com/javascript-in-plain-english/react-refs-both-class-and-functional-components-76b7bce487b8

like image 32
Reza Poorbaferani Avatar answered Mar 11 '23 01:03

Reza Poorbaferani