1
votes

I am new in reactjs and learning bit and pieces. I am facing an issue. The scenario is like. I have a functional component as a parent. It has a child component as a class component. I would like to set or reset the child component's state on parent's button click. Or is there any way to call the child component's any method from the parent component. I tried as

  // this call from a functional component.    
<PhotoPreviewUploaend setSelectedFile={setSelectedFile} ref={setImagePreviewUrl} /> 

Later after a button click does this:-

setImagePreviewUrl('');

I read ref attribute allows access to the component. I tried this ref between 2 class component both parent and child is class components and it works as expected. But when did the same from a functional component it has no effect at all. How can I do it?

1
When you tested it with both class components, which component held the state? - eMontielG

1 Answers

1
votes

You are not embracing react one-way data flow by using refs like that; it might not behave the way you expect;

You should pass parent state handler logic function to the child component, then child component call it with proper value; as the result your parent state will be updated and you have nice and clean one way data flow; you can use this in any kind of component, since you don't mess with this bindings in functional components;

This example demonstrates it in action:

function App() {
  // Define your state
  const [someState, setSomeState] = useState(0);

  return (
    <div className="container">
       <Child parentCallback={setSomeState} />
    </div>
  );
}

class Child extends Component {

  render(){
    return(
     <div>
        <button
          onClick={() => this.props.parentCallback(/*someValue*/)}
        >
        click me!
        </button>
      </div>
    )
  }
}