Wang_TWJ
Wang_TWJ

Reputation: 63

react: How to change the state of a child component(function component, not class component) from its parent?

I can change the state of child component which is class componet by ref,but how can I change the function child compment?

Upvotes: 0

Views: 859

Answers (2)

pilchard
pilchard

Reputation: 12919

Here is an example using forwardRef() and storing the child's state handler function in the passed ref using the useImperativeHandle() hook allowing it to then be called from the parent.

const App = () => {
  const childRef = React.useRef();

  return (
    <div>
      <Child ref={childRef} />
      <button type="button" onClick={() => childRef.current.toggleRed()}>Toggle child</button>
    </div>
  )
}

const Child = React.forwardRef((props, ref) => {
  const [red, setRed] = React.useState(false);

  React.useImperativeHandle(ref, () => ({
    toggleRed
  }));

  const toggleRed = () => {
    setRed(p => !p);
  }
  
  return (
    <div >
      <div className={`child ${red ? 'red' : 'gray'}`}></div>
    </div>
  );
})


ReactDOM.render(
  <App />,
  document.getElementById("root")
);
.child {
  height: 100px;
  width: 100px;
}
.red {
  background-color: tomato;
}

.gray {
  background-color: lightgray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Upvotes: 2

S.N.B
S.N.B

Reputation: 813

you will need to pass the parent state in to child component as prop.

childComponent

export function ChildComponent(props) {

   return(
      <div> <p>You have clicked it {props.count} Times</p></div>
  )
}

parentComponent

import {ChildComponent} from './child.js'
function ParentComponent() {
 const [count, setCount] = useState(0);
return (
    <div>
        <ChildComponent count={count}/>
         <button onClick={() => setCount(count + 1)}>
    </div>
)
}

Upvotes: 3

Related Questions