Search code examples
reactjsreact-propsreact-functional-component

Calling a function from outside functional component in react


Say I have a form outside a functional component like this:

   <TextField
        onChange={handleChange('name')}
        value={values.name}
        variant="outlined"
        label="Name"
        id="name"
        required
    />

And I have my component this way:

   export default function App() {
        const handleChange = (prop) => (event) => {
           setValues({ ...values, [prop]: event.target.value });
        };
   }

How do I call the handleChange() function from inside my component?


Solution

  • You could pass in the handleChange function as a prop to your functional component:

    const MyComp = (props) => {
        ...
        return <TextField
            onChange={props.handleChange('name')}
            value={values.name}
            variant="outlined"
            label="Name"
            id="name"
            required
        />
    }
    
    // Reference function here.
    <MyComp handleChange={handleChange}/>