Send a triggering function to two separate components

My objective is as follows:

render() {
    return (
        <div>
            <Child onTrigger={xxx} />

            <button onClick={xxx} />
        </div>
    )
}

Upon clicking the button, I wish for some action to take place in the Child component. How can this be achieved? It should not just be a simple boolean toggle, but rather a trigger that can be activated multiple times.

Answer №1

You have two choices:

1. Increase a counter in your parent state every time you click the button.

2. Add a reference to your child component and call the function using

this.refs.child.yourFunctionHere()
.

Here is an example of how to achieve this:

class Parent extends React.Component{
        constructor(props) {
          super(props);
          this.handleClick = this.handleClick.bind(this);
          this.handleClickWithRef = this.handleClickWithRef.bind(this);
          this.state = {
                triggerEvent: 0
          };
        }

        handleClick(e) {
          this.setState({
            triggerEvent: this.state.triggerEvent+1
          });
        }
        handleClickWithRef(e){
            this.refs.child.functionA();
        }

        render() {
            return <div>
                <Child ref="child" onTrigger={this.state.triggerEvent} /> 
                <button onClick={this.handleClick}>Click to trigger</button>
                <button onClick={this.handleClickWithRef}>Click to trigger using ref</button>
                </div>;
        }
}
class Child extends React.Component{
        constructor(props) {
          super(props);
        }
        functionA(){
           alert("With ref");
        }
        componentWillReceiveProps(nextProps){
                if(nextProps.onTrigger !== 0 && nextProps.onTrigger !== this.props.onTrigger){
                alert("Your event here");
            }
        }
        render(){
           return <div>Child Component</div>
        }
}

Check out the full working example here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

TranslateY animation glitching

I need help with expanding a box to 100% height after click, then collapsing and sticking to the bottom. I created a function in Vue framework to handle the animation, but it's not working smoothly. How can I make it less buggy? Check out the demo her ...

What is the process to deactivate a single button from a list?

I have a dynamic list of items, each with a corresponding delete button. I am trying to disable the individual buttons upon clicking them. While I can currently disable a single button using the disabled property and setState, this approach may not be idea ...

What is the process to manually trigger hot reload in Flutter?

I am currently developing a Node.js application to make changes to Flutter code by inserting lines of code into it. My goal is to view these updates in real-time. Is there a way to implement hot reload so that every time I finish writing a line in the file ...

Using Typescript to implement a conditional return type and ensuring that the value types are consistent together

I am working with a useSelectedToggle hook that helps in connecting the UI state to the open/closed status of a dialog where it will be displayed. The toggle defines the value as (T) when it is open, and null when it is closed. How can I enforce stricter ...

Bind a collection of Firestore documents dynamically using Vuexfire

I currently have a collection of firebase documents stored in a vuex state that is dynamically updated. My goal is to bind these documents with vuexfire dynamically as they are added or removed from the list. state: { docsToBind: [], // This array is dy ...

Pattern to identify a 32-character string comprising a mix of letters and numbers

I am in search of a JavaScript regex pattern that can identify strings with the following format... loYm9vYzE6Z-aaj5lL_Og539wFer0KfD pxeGxvYzE6o97T7OD2mu_qowJdqR7NRc gwaXhuYzE6l3r1wh5ZdSkJvtK6uSw11d These strings are always 32 characters long and conta ...

Why isn't changing the property of a Sequelize instance having any effect?

While I've successfully used the standard instance syntax in the past, I'm facing a challenge with updating an instance retrieved from the database in this specific section of my code. ... const userInstance = await db.models.Users.findOne({wher ...

What is the best way to run an npm script with grunt-run?

I currently have a npm task specified in my package.json file for running jest tests: "scripts": { "test-jest": "jest", "jest-coverage": "jest --coverage" }, "jest": { "testEnvironment": "jsdom" }, I would like to run this task using ...

Adjust the style of cursor - User Interface Expansion Panel Material Design

Using the MiU component "Expansion panel", I encountered an issue. By default, when the user hovers over the panel, the cursor is set to pointer. I attempted to change it to a default cursor, but my modification did not work. The code for my component is ...

Is it possible to utilize $.each() in combination with $.ajax() to query an API?

I am dealing with an array containing 2 values, and for each value, I need to make an AJAX query to an API to check the stock availability. If there is stock for both values, a certain message should be executed, otherwise, a different message. This check ...

What is the process for incorporating a script function into a React application?

Recently, I've been attempting to integrate the external application Chameleon into my React application. To achieve this, I need to incorporate the javascript function within my application. I prefer it to be invoked only in specific scenarios, so I ...

Flatbuffers does not exist in this context

Currently, I am working on a nodeJs application that involves the use of Google Flat Buffer. After installing flatc on my MacBook Pro, I compiled the schema below: namespace MyAlcoholist; table Drink { drink_type_name: string; drink_company_name: stri ...

Python is experiencing difficulties with copying xpath elements

I attempted to utilize some Python code to access Twitter and retrieve the "Happening now" text. Unfortunately, it was unsuccessful. import webbrowser print("Visiting Twitter.com...") webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/c ...

Improving the efficiency of my conditions in a function with Vue JS

Does anyone have any suggestions on how to optimize this function? I feel like it could be shortened to improve its efficiency. Any help or advice would be much appreciated. Function: onStudentActionSelect: function () { if (this.selectedRows.length ...

Can you point me in the direction of the Monaco editor autocomplete feature?

While developing PromQL language support for monaco-editor, I discovered that the languages definitions can be found in this repository: https://github.com/microsoft/monaco-languages However, I am struggling to locate where the autocompletion definitions ...

How can we remove an ID from one table when the delete API is triggered in a different table?

One scenario I'm facing involves having 2 tables in my database. Let's say I delete a row (Role) from the Role Table. The question is, how can I also remove the particular role ID associated with the deleted role from the User Table? The User Ta ...

Having difficulty kicking off a fresh React project on Windows

I've encountered an issue while setting up my React application on Windows OS. After running npm start, the application fails to load on localhost:3000, showing the error message Cannot GET /. Below is the project structure: - webpack.config.js - p ...

Combining two lists in immutable.js by flattening and zipping

When faced with two immutable lists, such as: const x = [5,6,7]; const y = [x,y,z,w]; Is there a straightforward method to combine/interleave them in order to obtain: const z = [5,x,6,y,7,z,w]; ...

Create intricate text on the canvas by individually rendering each pixel

In my canvas project, I am using "fillText" to display a string such as "stackoverflow". After that, I extract the image data from the canvas to identify each pixel of the text. My goal is to capture the x position, y position, and color of each pixel. Th ...

Trouble arises when managing click events within the Material UI Menu component

I've implemented the Menu Component from Material UI as shown below - <Menu open={open} id={id} onClose={handleClose} onClick={handleClick} anchorEl={anchorEl} transformOrigin={{ horizontal: transformOriginRight, vertical: t ...