Home > database >  React access attributes of a class component from its parent
React access attributes of a class component from its parent

Time:08-12

Imagine the following scenario:

class Input extends React.Component {
  render() {
    return <input value="123" />
  }
}

function App() {
  const inputRef = React.useRef();

  return (
    <Input ref={inputRef} />
  );
}

I want to access the input tag's value attribute in my App component. However, inputRef.current.value is undefined.

How can I access attributes of a class component in React?

CodePudding user response:

I will just pass the ref as a prop and use it in the class component.

import React from "react";

class Input extends React.Component {
  render() {
    const { inputRef } = this.props;
    return <input ref={inputRef} name="inputExample" defaultValue="123" />;
  }
}

export default function App() {
  const inputRef = React.useRef(null);

  const logValue = () => {
    console.log(inputRef.current ? inputRef.current.value : "No Input found");
  };

  return (
    <div className="App">
      <Input inputRef={inputRef} />
      <button onClick={logValue} type="button">
        Input current value
      </button>
    </div>
  );
}

Check the sandbox in case you want to see a live example: https://codesandbox.io/s/distracted-curran-f6bhbrs-f6bhbr?file=/src/App.js

CodePudding user response:

You need to forward the ref using forwardRef and set the ref to the input element as below.

Class component

class Input extends React.Component {
  render() {
    return <input ref={this.props.innerRef} />;
  }
}

const MyInput = React.forwardRef((props, ref) => (
  <Input innerRef={ref} {...props} />
));

function App() {
  const inputRef = React.useRef();

  const checkValue = () => {
    console.log(inputRef.current && inputRef.current.value);
  };

  return (
    <div>
      <MyInput ref={inputRef} />
      <button onClick={checkValue}>check value</button>
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

Function component

const Input = React.forwardRef((props, ref) => {
  return <input ref={ref} />;
});

function App() {
  const inputRef = React.useRef();

  const checkValue = () => {
    console.log(inputRef.current && inputRef.current.value);
  };

  return (
    <div>
      <Input ref={inputRef} />
      <button onClick={checkValue}>check value</button>
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

  • Related