Home > other >  How can I call a function in a component from other components in React?
How can I call a function in a component from other components in React?

Time:10-22

I have the following component structure:

enter image description here

This is the Input component. When the onChange event is triggered, the validate function is called.

import React, {FC, useState} from 'react';

interface InputProps {
    config : {}
}

/**
 * @param config
 * @constructor
 */
const Input: FC<InputProps> = ({config}) => {

    /**
     * @param inputValue
     */
    const validate: Function = (inputValue: any) =>
    {
        // Does input validation 
    }

    return(
        <div>
            <input 
                onChange={(event) => {
                    validate(event.target.value);
                }}
            />
        </div>
    );
}

export default Input;

This is my App.tsx. I would like to call validation of all inputs in the button onClick event.

import React, {useState} from "react";
import Form from './components/Form/Form';
import Input from './components/UI/Input/Input';
import Button from './components/UI/Button/Button';

const App = () => {

  return(
    <div className="app">
        <Form title="Simple form">
            <Input label="Email address"/>
            <Input label="Password"/>
            <Button config={{
                text: 'Sign in',
                onClick: (event) => {
                    // Here I would like to call the validatе method on the email address and  
                    // password inputs, but I don’t know how to do this yet.
                }
            }}/>
        </Form>
    </div>
  );
}

export default App;

CodePudding user response:

You need to lift up the validate function to do the validation on click of button. Pass reference of the function to the components like input.

CodePudding user response:

All the useful information exists in the comments section via experts, here is just an implementation of what you need.

Lifting State Up

we need to lift the state from the Input component to it's parent component.

in the App component:

import React, {useState} from "react";
import Form from './components/Form/Form';
import Input from './components/UI/Input/Input';
import Button from './components/UI/Button/Button';

const App = () => {
 const [email, setEmail] = useState("");
 const [password, setPassword] = useState("");

  return(
    <div className="app">
      <Form title="Simple form">
        <Input label="Email address" value={email} onAction={setEmail} />
        <Input label="Password" value={password} onAction={setPassword} />
        <Button config={{
           text: 'Sign in',
           onClick: () => {
             validate(emailAddress);
             validate(password);
           }}
        />
      </Form>
    </div>
  );
}

export default App;

Now, in the Input component:

const Input: FC<InputProps> = ({value, onAction}) => {
  return (
    <div>
      <input 
        value={value} 
        onChange={(event) => {onAction(event.target.value)}} 
      />
    </div>
  )
}

export default Input;

Explanation:

With changes on input element,the onAction function will invoke. onAction method is a setState function which you passed on the App component, so every change in the input element will update the email and password variables.

Now, in the App component, you have the password and email values, so validate them easily with your Button elements.

  • Related