Is it possible to incorporate the onClick feature of a component within another component in React?

I have embarked on creating a messaging app similar to WhatsApp.

To display the profile picture, I designed a card component that is accessible from a top bar component.

function DisplayPicture(prop){

    return(
        <div id="box">
            <div id="dp">
                <img src={prop.image}></img>
            </div>
            <div id="buttons">
                <div className="buttons_dp">
                    <FontAwesomeIcon className="ico" fontSize="1.5em" color="white"  icon={faMessage} />
            </div>
        </div>
    )
}

export default DisplayPicture;

This is how the top bar component looks:

function TopBar(prop){

    const [displayPicture, setDisplayPicture] = useState(false);

    function toggleDisplayPicture(){
        setDisplayPicture(!displayPicture);
        console.log(displayPicture);
    }

    return(
        <>
            <div id="bar_container">
                <div id="bar_left">
                    <FontAwesomeIcon fontSize="1.2em" color="#ebebeb"  icon={faArrowLeftLong} className="icon"/>
                    <div id="profile_picture" onClick={toggleDisplayPicture}>
                        <img src={prop.image}></img>
                    </div>
                </div>
                <div id="bar_middle">{prop.name}</div>
                <div id="bar_right">
                    <FontAwesomeIcon fontSize="1.1em" color="#ebebeb"  icon={faVideoCamera} className="icon"/>
                    <FontAwesomeIcon fontSize="1.1em" color="#ebebeb"  icon={faPhone} className="icon"/>
                    <FontAwesomeIcon fontSize="1.1em" color="#ebebeb"  icon={faCog} className="icon"/>
                </div>
            </div>
            <div id="dp_card" style={{display: displayPicture? "flex": "none"}}>
                <DisplayPicture image = {profile_picture} />
            </div>
        </>
    )
}

export default TopBar;

In the above setup, when clicking on the profile picture in the top bar component, it will display the dp_card component.

Now, when the dp_card component is displayed, I want the buttons within the dp_card to trigger an action inside the top bar component (specifically, hiding the dp_card when clicked).

So, my goal is to access the onClick event of a button in the DisplayPicture component from the TopBar component.

How can I achieve this functionality? Any guidance on this aspect would be greatly appreciated!

https://i.sstatic.net/EPLO7nZP.png

In the provided image showcasing the dp_card component, I aim to interact with the message button (leftmost) to hide the dp_card (setting its display to "none").

I am encountering difficulty in utilizing an onClick event from one component within another component.

Answer №1

Within the Top_bar component, include the dp and setdp methods along with the profile_picture. This will enable you to utilize the setdp function within the Show_dp component:

Implement changes in the Top_bar as shown below:

<div id="dp_card" style={{display: dp? "flex": "none"}}>
      <Show_dp image = {profile_picture} isDpVisible={dp} setDp={setdp} />
</div>

You can follow a similar approach within the Show_dp component:

function Show_dp(prop){

    function handleClick(){
        prop.setDp(false);
        console.log(prop.dp);
    }

    return(
        <div id="box" style={{display: prop.isDpVisible ? "flex" : "none"}}>
            <div id="dp">
                <img src={prop.image}></img>
            </div>
            <div id="buttons">
                <div className="buttons_dp" onClick={handleClick}>
                    <FontAwesomeIcon className="ico" fontSize="1.5em" color="white"  icon={faMessage} />
            </div>
        </div>
    )
}

export default Show_dp;

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

Can one monitor a Vuex module in real time?

I have a single module imported into the Vuex store: import date from './modules/date-select'; export default new Vuex.Store({ modules: {date}, }); Is it possible to "watch" for changes in the entire module within a component? For example: ...

When a user taps on a link or anchor within a specific webpage on an iPhone, the font size will automatically increase

The issue is specific to iPhones. I have tested it on an iPhone 5 (landscape mode) and an iPhone 4s (landscape mode). For a visual demonstration, you can view the video here. I attempted to fix the problem by specifying the font size, but unfortunately, ...

What could be the issue causing my code to not properly update CSS properties?

My jQueryMobile project involves overriding the CSS for listviews with the following code: li{ height:90px !important; border-style: 0px !important; border-width: 0px 5px 2px 0px !important; -moz-border-image: url('images/FA-iPhone_my-goals_READY-(2) ...

Utilizing Laravel 5.3 and Vue.js for Dynamic AJAX Calls Based on Select Box Selections

I am looking to display a newly added record in a select box once it has been inserted into the table. Below is my Laravel HTML code: <div class="form gorup"> <select class="form-control" > <option @click="called" ...

Incorporating additional text following the creation of an image composite using HTML5

I am facing an issue with positioning two images on a canvas using HTML5. Despite changing the x and y properties, the images remain stuck at the top left corner (0, 0). This is different from how I can position text easily on the canvas. <canvas width ...

Is there a way to monitor real-time updates without relying on setInterval or timeout functions?

Currently in the process of building a social network, I am working on fetching live notifications. The current approach involves sending an AJAX request every few seconds using setInterval. The code snippet for this operation is as follows: setInterval ( ...

Remove HTML tags from a table cell containing a combination of radio buttons and labels

Javascript Function: My JavaScript function posted below is designed to iterate through the column indexes specified in the 2nd parameter and also iterate through the element ids provided in the 3rd parameter. It will then populate the textbox, radiobutto ...

What is the best way to set a newly selected HTML option as the first choice?

I'm facing a simple problem in JavaScript that I can't seem to crack. Admittedly, I am new to working with JavaScript. My issue lies with sorting a dropdown list in alphabetical order while also keeping the selected value at the top. Whenever a ...

What impact does converting my div class into a form have on the overall operation of my website?

I am in the process of creating a file upload feature for my website. However, when I attempted to convert the div with the ID "cool-border" into a form element to facilitate file uploading, the functionality of my code ceased to work properly. After selec ...

Reached 10 iterations in the Digest, stopping due to a scope function problem

When processing data, I encounter a unique challenge where the information is returned in an unusual format (a single string representing all the options/labels of a radio button group). For example: "yes|Yes no|No" To address this issue, I have develop ...

What is the best way to implement media queries in a column layout for a responsive webpage?

My goal is to display a picture below the navbar when the window size becomes small or in mobile mode, followed by my name and other details. However, I am having trouble understanding how to implement this using media queries. DESKTOP PREVIEW https://i. ...

Having trouble getting the onPress event to function properly on a custom button component in my React Native application

As a React Native beginner, I am currently working on a project where I am trying to create a custom button named "RoundedButton" using TouchableOpacity. However, when I attempt to trigger an event using onPress like , it does not seem to work for me. Here ...

The "length" property of Jade is undefined in a simple loop situation

Utilizing a jade template with data queried from mongoDB through node. The get request is managed by Express... app.get('/rendered', function(req, res){ console.log(mongoDoc[0].date + " date 0"); console.log(mongoDoc[1].date + " date 1" ...

The @Input() property within an Angular component is producing an empty array as its result

I have a calendar component that has a data property marked as @Input(): import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-calendar', templateUrl: './calendar.comp ...

Guide on creating a multi-column message in a Telegram bot using Google Script

After using this code to create my bot, everything was working perfectly. However, I encountered an issue when attempting to type a longer message and hitting enter to create newline breaks - the message wouldn't save. As shown in the image, the bot ...

Using responseJson data from a database in a picker component in a React Native application

After fetching a JSON response, I needed to use it in a picker. However, when running the code, I encountered this error: TypeError: undefined is not an object (evaluating 'this.state.dataSource.map') Interestingly, using a flat list works witho ...

The directive 'templateUrl' points to the route '/'

I'm having an issue with using the templateUrl in a directive to load a partial. Whenever I try to visit the URL for the template, it redirects me back to /. This results in the partial loading the entire page instead of just the requested partial. a ...

Update the URL and parse the data in a Backbone collection

For the purpose of development, I am looking to replace the collection with fake JSON results either from a JSON variable or a JSON file. However, I encountered an error when attempting to do so using url http://jsfiddle.net/qhoc/uZhM8/ GET http://fiddle ...

"My drop down button menus and background image seem to be experiencing some technical difficulties. Can someone help

I'm having trouble getting a drop-down menu to work with a reptile image as the background. When I remove the image, the drop-down works fine. I've checked for errors but can't seem to find any. Is it an issue with the code or maybe a typing ...