How can we display or conceal text indicating the age of a patient based on the value returned from selectedPatient.age in a React application?

Hello, I am looking to dynamically display the age in years on the screen based on the value retrieved from selectedPatient.age, toggling between visible and hidden states.

import React, { useContext } from 'react';
import { useHistory } from 'react-router-dom';
import { PatientContext } from '../App';

const ContentHeader = () => {
    let { selectedPatient, setSidebarPatients, sidebarPatients } = useContext(PatientContext);
    const history = useHistory();

const deletePatient = async () => {
    const newSidebarPatients = sidebarPatients.filter(el => el.id != selectedPatient.id);
    setSidebarPatients(newSidebarPatients);
    history.push('/');
};

const pushEditComponent = () => {
    history.push('/patient/edit');
};

return (
    <div className='header'>
        <p className='firstname'>{selectedPatient.firstname}</p>
        <p className='lastname'>{selectedPatient.lastname}</p>
        <p className='age'>{selectedPatient.age} years old</p>

        <div> 
            <button onClick={pushEditComponent} className='edit-btn'>Edit</button>
            <button onClick={deletePatient} className='delete-btn'>Delete</button>
        </div>
    </div>
);
}

export default ContentHeader;

View image for always visible years

Answer №1

Implement conditional rendering in this section Refer to: https://reactjs.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

... 
return (
    <div className='header'>
        <p className='firstname'>{selectedPatient.firstname}</p>
        <p className='lastname'>{selectedPatient.lastname}</p>
        {selectedPatient.age? <p className='age'>{selectedPatient.age} years old</p>: null} 

        <div> 
            <button onClick={pushEditComponent} className='edit-btn'>Edit</button>
            <button onClick={deletePatient} className='delete-btn'>Delete</button>
        </div>
    </div>
);
} 
... 

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

Having trouble maintaining the original events on a cloned element

My goal is to duplicate an element passed into a function and retain all associated events, including ones like $('.example').on('click', function(e) ... )} that are defined within the document ready. Here's what I'm trying: ...

Despite functioning properly when triggered from the debug console, the jQuery AJAX request fails to work upon page load

The issue was resolved by disabling asynchronous requests in jQuery. Here is the Javascript & AJAX request (using jQuery) code on my page: "use strict"; var hsArea, counter, hotspots, count; counter = 4; count = 0; hotspots = {}; function fetchHots ...

Halt period indicated in the document specifying the designated timeframe

If I have two files named index.php and fetch.php The contents of index.php are as follows: <script> $(document).ready(function(){ setInterval(function(){ $('#fetch').load('fetch.php') }, 1000); }); </sc ...

How a JavaScript function handles the scope of a for loop index

Here's some Javascript code I'm working with: func1() { for(i = 2; i < 5; i ++) { console.log(i); func2(i); } } func2(x) { for(i = 100; i < 200; i ++) { do something } } I've noticed that when runni ...

tips for closing mat select when clicked outside

When a user clicks on the cell, it should display the value. If the user clicks outside the cell, the input field will close and show the field value. I am facing an issue on how to implement this with mat select and mat date picker. Any suggestions? Than ...

Sending a Javascript object to PHP for decoding as JSON can be accomplished by

After searching through numerous similar posts without success, I am still struggling to get this dynamic 2-dimensional JavaScript object to work. My goal is to pass it to PHP in order to insert it into a MySQL table. Utilizing an Ajax post seems to be the ...

I am looking to transmit the text inputted into a modal using React.js to the Backend server

Working on the front-end of a web app with React.js to control home appliances. The goal is to send modal text to the backend without reloading the page. Encountering an issue where submitting the modal text causes a page reload, hindering console visibi ...

What is the method for creating a function using the const keyword in JavaScript?

I trust you are doing well. Recently, I have embarked on a coding journey and encountered an interesting challenge. The task requires me to create a function that outputs specific weather conditions for different countries to the console: The weather in ...

I could use some assistance with accessing the /results page on the OMDb API following a movie search by

Presented here is my app.js code. My objective is to develop a movie search feature that enables me to look up a movie in a database and retrieve results for 10 movies related to the entered keyword. For instance, if I input "ALABAMA", the system should re ...

The latest React 0.60.4 update causes an Android build failure with the error message "symbol not found"

Just made the switch to React <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89c7e8fde0ffecc9b9a7bfb9a7bd">[email protected]</a>. Everything's running smoothly on iOS and xcode after updating, but I hit a sn ...

Retrieving text from an XPath element with Selenium WebDriver in JavaScript

I've been experimenting with Selenium and Node to extract text content from websites. For instance, I'm currently working with the URL: and using this XPath /html/body/section/div[1]/div[3]/div[1]/div[3]/form/button When I check in an Xpath se ...

What is the process for populating the Body placeholder in asp.net Core MVC?

After reviewing a tutorial, I discovered that the RenderBody method is supposed to display views within the designated placeholder of the layout, as illustrated in this diagram: However, in practice, it did not work exactly as expected. When I created a l ...

Enhance the overall appearance of select elements across all components using Material UI's

I'm attempting to change the border color of my outlined select elements using the code below, but it's not working as expected. It seems that the border style is being inherited from the fieldset element. I've experimented with using MuiOut ...

Encountering a blank page and error message on Vue JS while attempting to generate a JSON file within the

Recently, I encountered a peculiar problem while working on my Vue project using Vue UI in Visual Studio. Before connecting my API, I wanted to prototype and experiment with fake data. So, I decided to create a JSON file in the assets folder to store my m ...

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

Using React MUI Select in combination with react-hook-form does not seem to be compatible with Cypress testing

Within my React application, I have implemented a form that includes a dropdown select. Depending on the option selected from the dropdown, different input fields are rendered. const [templateType, setTemplateType] = useState(""); const { regi ...

Choose a color from the material-ui-color picker and set it when the mouse is released

Has anyone experienced difficulties with setting the value onChange in the material-ui-color ColorPicker plugin? The issue I'm facing is that every time I start dragging the mouse within the ColorPicker, it triggers the onChange function continuously ...

Developing Angular 2 custom async validators for use in reactive forms

I am currently working on a reactive form that requires unique form controls: this.form = new FormGroup({ name: new FormControl(this.initialValue, [ Validators.required, ], this._uniqueNameValidator.bind(this)), }); To achieve this, I have create ...

How can I make my iPad switch to landscape mode in my specific situation?

I'm attempting to trigger the landscape mode on an iPad web browser, including the address bar and tabs, when a user clicks a link. Here's what I currently have: <div> <a ng-click="click me()" href="www.cnn.com">Click me</a&g ...