React: Callback Functions and Buttons

Brian Smith
3 min readJul 8, 2021

--

React can be overwhelming and confusing for a beginner. I was one of those confused beginners, especially when it came to callback functions in React. Thankfully, with help from a friend, I was able to better understand how callback functions work in React. Hopefully the information below will help someone else who may be struggling with callbacks in React.

The application that I was working on had four components. The parent component — App.js — and three child components — Likes.js, Comments.js, and Videos.js. This post will focus on the App.js and Likes.js components.

The goal of this project was to create a button that when clicked would hide the username and comments on the page. This button was located in the Likes.js component but the feature that needed to hide the <div> was located in the App.js file. I will explain from start to finish how I accomplished this task and how you can call a callback function on a button to hide a <div>.

I started by setting up a State on line 14 on the first image and setting the State’s value to true.

const [commentsOn, setCommentsOn] = useState(true)

Then, on line 12 I set up the function that needs to be passed through to the Likes component which happens on line 26.

function toggleComments(callbackCommentsOn) { setCommentsOn((callbackCommentsOn) => !callbackCommentsOn)

}

Whatever you pass through to components needs to be added to your props so that you can access them. I add both the toggleComments and commentsOn as props to be called.

I then set up another function inside the Likes component so that I can call the function on an event listener, which will be onClick. When that button is clicked the callback function will be called.

On line 35 of the second image I set up my button with the event listener as well as a ternary statement to change the text of the button once it is clicked. When the State of CommentsOn is changed the text will change on the button. Once that button is clicked the function on line 21 of the second image will be called.

function handleClickComments(){

toggleComments(commentsOn)

}

This is where the callback function occurs, calling back to the toggleComments function that I passed through. This function will now be called on line 12 of the first image. This will change the current State of commentsOn to false which in turn will change the ternary statement on line 27 of the first image and line 35 of the second image to false.

This ultimately changes the text of the button to “Show Comments” and hides the comments using the style “display” : “none”.

--

--