Olawale Oladiran
Olawale Oladiran

Reputation: 631

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?

Upvotes: 1

Views: 621

Answers (2)

lala
lala

Reputation: 1439

if you've a form component as a child component of a component, then you can do something like so:-

  • ParentComponent.js:-
import ChildComponent from './ChildComponent'

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

  return (
    <ChildComponent 
      handleChange={handleChange} 
    />
  )
}
  • ChildComponent.js:-
export default function ChildComponent({handleChange}) {
  return (
    <TextField
      onChange={handleChange('name')}
      value={values.name}
      variant="outlined"
      label="Name"
      id="name"
      required
    />
  )
}

Upvotes: 1

code-gorilla
code-gorilla

Reputation: 2408

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}/>

Upvotes: 1

Related Questions