Call function in parent component without using props

Cannon Moyer

I have a an App component that renders a CustomerForm component like so:

App.js

class App extends Component{
    constructor(props){
        this.state = {logged_in: true};

    }

    logout = () => {
      this.setState({logged_in: false}):
    }
    render(){
        return(
            <div>
                <CustomerForm />
            </div>
        )
    }
}

In my CustomerForm component, I have an onSubmit function that is called when the form submits:

CustomerForm.js

class CustomerForm extends Component{
    
    constructor(props){
         this.state = { submitting: false }
    }

    handleSubmit = (e) => {
       e.preventDefault();
       this.setState({submitting: true});
       try{
           //API CALL HERE
       }catch(e){
           //if error == unauthorized, then logout. 
       }

    }
}

When I render the CustomerForm component from the App component, I realize that I could pass a reference to logout via a prop, however, my application is much larger than the one I have provided here. Ultimately, I want to be able to call the logout() function that is in the App component from either like a helper file or any nested component (preferably a helper file). Once this function is called, the state for the App component would be updated to reflect that the user is now logged out. I tried to use createContext and this allowed me to pass the attributes and functions I needed, however the functions were only available in the JSX like so:

<authContext.Consumer>
    {({logout}) => {
      return (
    
        <Form onSubmit={logout}/>
      );
    }}
</authContext.Consumer> 

However, I need to be able to access logout from within the handleSubmit function. I know that I can pass the logout function as a reference to handleSubmit, but I figure there is a cleaner way to do this.

Nilesh Patel

With Context api and HOC, you can do that. let me know your thought.

app.js

/ Create a new context for the app
export const AppContext = React.createContext('app');

class App extends Component{
    constructor(props){
        this.state = {logged_in: true};
    }

    logout = () => {
      this.setState({logged_in: false}):
    }
    render(){
        return(
            <AppContext.Provider
                value={{
                    state: this.state,
                    logout: this.logout
                }}
            >
                <CustomerForm />
            </AppContext.Provider>
        )
    }
}

Create a HOC for your Context

withAppContext.js

import {AppContext} from './app.js'

export function withAppContext(Component) {
    return function WrapperComponent(props) {
        return (
            <AppContext.Consumer>
                {state => <Component {...props} context={state} />}
            </AppContext.Consumer>
        );
    };
}

CustomerForm.js

import { withAppContext } from 'withAppContext.js'

class CustomerForm extends Component{
    
    constructor(props){
         this.state = { submitting: false }
    }

    handleSubmit = (e) => {
       this.props.context.logout();
    }

  render() {
    return (
      <>
        <div>Child</div>
        <button onClick={this.handleSubmit}>logout</button>
      </>
    );
  }

}

export default withAppContext(CustomerForm); 

codesandbox demo

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to call Child function from Parent / Pass Props to a Parent component without using ref methods?

From Dev

ReactJS call parent function from grandchild without using props

From Dev

How to pass this.props from parent to child component while using map() function without getting undefined?

From Dev

How to call `this.props.children` 's function from parent component?

From Dev

Call a function in react component, WITHOUT event handlers or props

From Dev

Using a button in parent component to call function in child component

From Dev

React, updating state in child component using props after async call in parent component

From Dev

vue2 call a parent function using $emit from component

From Dev

Unable to call child function from parent using refs with functional component

From Dev

how to call function in parent component

From Dev

async Function call to Parent Component

From Dev

Passing child component data to parent using props

From Dev

Call a parent component function from a child component

From Dev

How to conditionally call different optional function props in a React TypeScript component without getting compiler error?

From Dev

ReactJS Component function call this and props undefined

From Dev

Unable to call props function in child component react

From Dev

Call update function from component without using task

From Dev

Access children in function component without the props parameter

From Dev

Add props from parent component in map() function from child component

From Dev

React: Pass function to child component as props, call onClick in child component

From Dev

Any better way to pass data from a child component to a function in a parent component without using bind()?

From Dev

How to pass a function down the component's hierarchy without using props in React?

From Dev

Parent component to call child component function on a list of children component

From Javascript

How to call function on child component on parent events

From Dev

Call child component function from parent

From

angular2 call function of parent component

From Dev

How to call parent component function on button click?

From Dev

Call function in child component only after function in parent component is completed

From Dev

Not able to access public properties of parent component in props passed function in angular

Related Related

  1. 1

    How to call Child function from Parent / Pass Props to a Parent component without using ref methods?

  2. 2

    ReactJS call parent function from grandchild without using props

  3. 3

    How to pass this.props from parent to child component while using map() function without getting undefined?

  4. 4

    How to call `this.props.children` 's function from parent component?

  5. 5

    Call a function in react component, WITHOUT event handlers or props

  6. 6

    Using a button in parent component to call function in child component

  7. 7

    React, updating state in child component using props after async call in parent component

  8. 8

    vue2 call a parent function using $emit from component

  9. 9

    Unable to call child function from parent using refs with functional component

  10. 10

    how to call function in parent component

  11. 11

    async Function call to Parent Component

  12. 12

    Passing child component data to parent using props

  13. 13

    Call a parent component function from a child component

  14. 14

    How to conditionally call different optional function props in a React TypeScript component without getting compiler error?

  15. 15

    ReactJS Component function call this and props undefined

  16. 16

    Unable to call props function in child component react

  17. 17

    Call update function from component without using task

  18. 18

    Access children in function component without the props parameter

  19. 19

    Add props from parent component in map() function from child component

  20. 20

    React: Pass function to child component as props, call onClick in child component

  21. 21

    Any better way to pass data from a child component to a function in a parent component without using bind()?

  22. 22

    How to pass a function down the component's hierarchy without using props in React?

  23. 23

    Parent component to call child component function on a list of children component

  24. 24

    How to call function on child component on parent events

  25. 25

    Call child component function from parent

  26. 26

    angular2 call function of parent component

  27. 27

    How to call parent component function on button click?

  28. 28

    Call function in child component only after function in parent component is completed

  29. 29

    Not able to access public properties of parent component in props passed function in angular

HotTag

Archive