Getting child properties of a react function component

72 Views Asked by At

I have created a simple sample here: https://codesandbox.io/s/crimson-monad-r6tns?fontsize=14&hidenavigation=1&theme=dark

When you click the text 1 it increment the value in the child component. In the parent i have a button where I want to access the value in the child component from the parent component. Not with an event but something like ChildComponent.YourCurrentValue. Is that possible in REACT? Can you add an id to the child component in the render method and then access it's properties by that?

1

There are 1 best solutions below

1
On BEST ANSWER

You have to pass the changes to the parent by calling a prop function in child like this:

import React, { useState } from "react";

const ChildComponent = props => {
  const [selectedValue, setSelectedValue] = useState(1);

  function clicked() {
    const newCounter = counter + 1;
    setSelectedValue(newCounter);

    props.onChange(newCounter)
  }

  return <div onClick={clicked}>{selectedValue}</div>;
};

export default ChildComponent;

And get it back in parent component such as below:

import React from "react";
import "./styles.css";
import ChildComponent from "./ChildComponent";

export default function App() {
  function showChildProperty(newCounterValue) {
    alert(newCounterValue);
  }

  return (
    <div className="App">
      <button onClick={showChildProperty}>Show child property</button>
      <ChildComponent onChange={showChildProperty} />
    </div>
  );
}

Hope you found your answer as you wanted.