Git Product home page Git Product logo

Comments (5)

panzerdp avatar panzerdp commented on August 26, 2024 3

With the your example, we simply only change props name which pass to child compnent. What do you think about it ?

@vietphongtech That's a wonderful question!

Keeping ref attribute (instead of a custom one like elementRef) is better because it keeps the ref API consistent between class-based, function-based, and HTML tags.

Please also check this Stackoverflow answer.

from dmitripavlutin.com-comments.

RavenColEvol avatar RavenColEvol commented on August 26, 2024 2

Apparently while reading the article I had the same doubt as @vietphongtech mentioned because I've myself done the ref passing and using it from parent to child without forwardRef.
This article did help understanding why it worked and a good pattern to follow.

Also this thinking triggered me while reading useImperativeHandle that it can lead to a design pattern somehow, like a Form with every input element with useImperativeHandle so every input has there own flavour of implementation but same API's to be handled from parent. This probably not a proper example but just thinking out loud. We already have a pattern to solve this i guess like renderProps but this is also something cool.

from dmitripavlutin.com-comments.

vietphongtech avatar vietphongtech commented on August 26, 2024

I thing we can still access a DOM element of a child component from its parent.
With the your example, we simply only change props name which pass to child compnent.

import { useRef, useEffect } from 'react';

function Parent() {
  const elementRef = useRef()
  useEffect(() => {
    console.log(elementRef.current);
  }, [])
  return <Child elementRef={elementRef} /> // assign the ref
}

function Child({ elementRef }) { // a new component
  return <div ref={ref}>Hello, World!</div>
}

I had somes experiment and all of them work for me.
What do you think about it ?

from dmitripavlutin.com-comments.

panzerdp avatar panzerdp commented on August 26, 2024

Apparently while reading the article I had the same doubt as @vietphongtech mentioned because I've myself done the ref passing and using it from parent to child without forwardRef.

@RavenColEvol I had a bit different feeling: because props in React must be immutable, I wasn't considering using elementRef={elementRef} as a prop because eventually elementRef.current is being mutated.

Also this thinking triggered me while reading useImperativeHandle that it can lead to a design pattern somehow, like a Form with every input element with useImperativeHandle so every input has there own flavour of implementation but same API's to be handled from parent.

Good idea. useImperativeHandle() can provide an imperative method getFormData() { ... }: which would return an object where with inputs names and values. For example:

import { useRef, useImperativeHandle, forwardRef } from 'react'

export function Main() {
  const formControllerRef = useRef()

  const onClick = () => {
    console.log(formControllerRef.current.getFormData()); // { firstName: '...', lastName: '...'}
  }

  return (
    <>
      <button onClick={onClick}>Get form data</button>
      <Form ref={formControllerRef} />
    </>
  )
}

const Form = forwardRef(function (props, ref) {
  const firstNameRef = useRef()
  const lastNameRef = useRef()

  useImperativeHandle(ref,
    () => {
      return {
        getFormData() {
          return {
            firstName: firstNameRef.current.value,
            lastName: lastNameRef.current.value,
          };
        },
      };
    }, [])

  return (
    <>
      <input ref={firstNameRef} type="text" placeholder="Enter first name" />
      <input ref={lastNameRef} type="text" placeholder="Enter last name" />
    </>
  )
})

See the demo.

Although care must be taken so that the parent component doesn't know too much about the child's internal structure.

from dmitripavlutin.com-comments.

universalcosmologist avatar universalcosmologist commented on August 26, 2024

(sorry if it is silly or basic i am new to react) when we are sending ref prop to child which is wrapped in forwardRef the prop passed is still changed from null to that of dom element so how exactly here props are immutable is preserved

from dmitripavlutin.com-comments.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.