DEV Community

Vadim Stakhnyuk
Vadim Stakhnyuk

Posted on

Passing Down Functions As Props in React

Approaching the end of my journey at Flatiron School, one of the more interesting and hard subjects to learn was React. After learning pure vanilla JavaScript and being able to write an application with it, we learned the capabilities of react and how useful it is as a framework. With the transition to react, we are introduced to JSX, which is an implementation of both JavaScript and html all in one. One of the hardest things about the transition was the general use of the framework. In JavaScript, we had separate files for html and javascript. Whereas now, it’s all JSX and multiple components of an application. We are introduced to state and props, and the component lifecycle. Creating functions and making them work with state was a challenging part of the learning curve. I had a problem in a project where in the child component, I had an onClick function, and I needed that onClick function where state was, which was in the parent component. I got stuck on how to pass my function down from the parent component to the child component. When I was doing research on how to pass down functions as props into different components, I saw a lack of information on the web. So I decided to write this blog in case anyone else feels confused in this part of the React learning process.

Creating Functions at the State Level Components

When working with state, we typically want state to be in only 1 component. In other terms, we want the lowest number of components with state as possible. This means that in order to change state in a different component, we have to pass down our functions as props to the component that needs to change state. This way, we can have functions in our child components that are able to change state. This is very useful for cases where you have a child component that has an onClick function or an onChange function that needs to change state in order for the user to see the correct information on the screen.

Passing Down Functions As Props

The process of passing down functions as props can be very confusing. It happens during the render, where you call a new component. During that component call, you pass in your function as a prop. In my demonstration, I pass in the prop as "clickMe".



import React from 'react';
import './App.css';
import NewComponent from './components/NewComponent';
// import NewFunctionalComponent from './components/NewFunctionalComponent';

class App extends React.Component {

  constructor(){
    super()
    this.state = {
      isClicked: false
    }
    console.log(this.state)
  }

  handleClick = () => {
    console.log('I have been clicked')
    this.setState({
      isClicked: true
    }, () => console.log(this.state.isClicked))

  }

  render() {
    return (
      <div className="App">
        <NewComponent clickMe={this.handleClick} />
        {/* <NewFunctionalComponent noClickMe={this.handleClick} /> */}
      </div>
    )
  }
}

export default App;


Enter fullscreen mode Exit fullscreen mode

With this simple demonstration, I have created a react application that changes the state with the click of a button. In the render, when I reference the "NewComponent" component, I pass the "handleClick" function down into the child component. This way, I can reference that function in my child component.



import React from 'react';

class NewComponent extends React.Component {

    clickMe = () => {
        this.props.clickMe()
    }

    render() {
        return (
            <div>
                <button onClick={this.clickMe}>Click Me!</button>
            </div>
        )
    }
}

export default NewComponent;


Enter fullscreen mode Exit fullscreen mode

In this child component, I have an onClick event handler. I also created a helper function during the onClick event. Now, our onClick event can be functioning due to the fact that it is passed down as props into our "NewComponent" component. I can also pass back props or an event back to the parent component is I include it in my function. Here is an example,



//You can pass in props back to the parent element like this.

clickMe = () => {
    this.props.clickMe(props)
}


Enter fullscreen mode Exit fullscreen mode

OR...



//You can also pass an event. I am passing in the value of the event as an example

clickMe = (event) => {
    this.props.clickMe(event.target.value)
}


Enter fullscreen mode Exit fullscreen mode

Same Scenario But Using A Functional Component



import React from 'react';

const NewFunctionalComponent = (props) => {
    return (
        <div>
            <button onClick={() => props.noClickMe()}>No, Click Me!</button>
        </div>
    )
}

export default NewFunctionalComponent;


Enter fullscreen mode Exit fullscreen mode

Demonstration

I have included some console logs to show the process of state changing. Before any kind of action is done, the default state is "false". After the click event, the state changes becomes "true". This is to show that throwing functions into different components actually works.

Conclusion

React is basically magic. It is a very powerful tool when it comes to making online web applications. The use of state and props is vital for presenting things to the user. I have created a simple demonstration showing the capabilities of being able to pass functions down as props. This way, you can have the ability to maneuver around in different components and still have state in only one component. It is scary to see how many helpful functions we have with React, and the more you learn about React, the more exciting it becomes. As the possibilities become endless with what you can create.

Top comments (4)

Collapse
 
petewk profile image
petewk

Thank you so much, you've somehow made this so simple.
I've been trying to learn React and after following a bunch of tutorials I decided to go back to the basics and realised I didn't understand using props, which seems like a huge part of React.
I've been pulling my hair out for two days straight trying to simply get state updated from a Child component, and you've simplified it perfectly!
Hero!

Collapse
 
husseinkizz profile image
Hussein Kizz

Thanks for the post sure, however, it didn't rock well for me, I just want to pass a onchange event handler to usestate() without creating a new component i.e I instead want something like
const [items, setItems] = usestate(prop);

Collapse
 
prithviraj2511 profile image
Prithviraj Patil

Nice blog !!! helped me to understand this concept in the easiest way. Keep writing blogs like this.

Collapse
 
abdelhamidlarachi profile image
nginX-iwnl

so clean! thanks a lot