React JS

Explain, How to Pass Props, parameter and Functions to Child Components

Explain, How to Pass Props, parameter and Functions to Child Components

How to Pass Props, parameter and Functions to Child Components

This Articles Explain you, How to Pass Props, parameter and Functions to Child Components

In ReactJs, components allow you to break up the user interface into separate, reusable chunks of code.
Similar to JavaScript functions, components are. They take unrestricted inputs, or "props," and return React elements that describe what should be displayed on the screen.



TypeScript Version

Parent Component

interface Props {
    property: Property;
}
export default function ParentComponent({property}: Props) {
    const [user, setUser] = useState("");
    const setUser= (id: string): void => {
      setUser(id);
    }
   
    return (
      <>
          <ChildComponent
              name={property.name}
              handleruser={setUser} />
      </>
)}

Child Component

interface Props {
    name: string;    
    handleruser: (id:string) => void;    
}
 
export default observer(function ChildComponent({ name, handleruser}: Props) {
    const { userProfileStore } = useStore();
    const { loadProfiles, UserProfiles} = userProfileStore;

    const handleOnChange = (e: any) => {
        handleruser(e.target.value);        
    };

    useEffect(() => {
        loadProfiles();
    }, [loadProfiles]);
   
  return (    
    <select
        name={name}
        id={name}
        onChange={handleOnChange }
    >        
        {UserProfiles.map((user, i) => <option value={user.id} key={user.displayname}>  
             {user.displayname}</option>)}    
    </select>  
  );
});


This way, we can pass whatever value selected in Child Component back to its Parent Component, Where Parent can save the same in database.



JavaScript Version

Parent Component

class ParentComponent extends React.Component {
  renderSquare(i) {
    return <Child name={i} />;
  }
}

Child Component

class ChildComponent extends React.Component {
  render() {
    return (
      <button className="btn">
        {this.props.name}
      </button>
    );
  }
}











Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram