React: Passing Data from Child to Parent Components

Parent component:


import { useState } from "react";

import Child from './Child';



const Parent = () => {

  const [message, setMessage] = useState<string>("");



  const handleNewMessage = (newMessage: string) => {

    setMessage(newMessage);

  };



  return (<div>

	  <h3>{message}</h3>

	  <Child handleNewMessage={handleNewMessage} />

  </div>);

};



export default Parent;

Child component:


import { useState } from "react";



interface ChildProps {

  handleNewMessage: (newMessage: string) => void;

}



const Child: React.FC<ChildProps> = (props: ChildProps) => {

  const [newMessage, setNewMessage] = useState<string>("");



  const handleNewMessage = () => {

    props.handleNewMessage(newMessage);

    setNewMessage("");

  };



  return (<div>

      <input type="text" value={newMessage}

        onChange={(event)=>setNewMessage(event.target.value)}

      />

      <Button onClick={handleNewMessage}>Change Message</Button>

  </div>);

};



export default Child;

Leave a Comment