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

ESLint version 8.0.0 encountered an error while attempting to fetch the '@typescript-eslint' plugin

Hey there, I'm in need of some assistance. I encountered an error while trying to build a project. Uh-oh! Something didn't go as planned! :( ESLint: 8.0.0 TypeError: Failed to load plugin '@typescript-eslint' specified in ' ...

I desire to alter the description of an item within a separate div, specifically in a bootstrap

I used the map method to render all the images. However, I need a way to track the current image index so that I can change the item description located in another div. Alternatively, if you have any other solutions, please let me know. App.js : import Ca ...

Encountering a 404 error with Next.js 13 dynamic routing

Whenever I click on an item, it redirects to the dynamic route "http://localhost:3000/products/{id}" but instead of displaying the data, I get an error. Here is my file structure: app components Product.js pages Products [id].js layou ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...

Switching from constructors to Hooks in REACT

I am currently working on adding a modal example within a function in my project. I have a specific requirement to incorporate hooks instead of using the constructor in a class-based component. This is the code snippet with the class-based implementation: ...

Utilizing an external SCSS or CSS file with Material UI in React: A step-by-step guide

Encountering issues with external CSS files in my React project that uses Material UI components. Despite creating a CSS file for each component in the react components folder, they fail to load upon hard reloading the site. I prefer using external CSS ov ...

How can I efficiently update child states within a parent class using ReactJS?

Exploring the parent component class Root extends React.Component { constructor(props) { super(props); this.state = { word: Words, }; } c ...

The align-items property in Flexbox is not functioning as expected when applied to Link components contained within

I'm in the process of creating a simple navigation bar using flexbox, but I'm encountering an issue where the content within the unordered list is not vertically centered. Below is the HTML code snippet: *,*::before,*::after{ margin: 0; ...

Troubleshooting textarea resize events in Angular 6

In the development of my Angular 6 application, I have encountered an issue with a textarea element. When an error occurs, an asterisk should be displayed next to the textarea in the top-right corner. However, there is a gap between the textarea and the as ...

What might be causing the onclick action in a ReactJS app using Redux to not work as

Below is the simplified code snippet: -action.js export const removeVisitedUser = id => async dispatch => { try { const visited = JSON.parse(localStorage.getItem(`visited_`)) || []; const filtered = visited.filter(i => ...

"Why does the useEffect in Next.js fire each time I navigate to a new route

Currently, I have implemented a useEffect function within the Layout component. This function is responsible for fetching my userData and storing it in the redux-store. However, I have noticed that this function gets triggered every time there is a route c ...

Arrange a pair of div containers side by side on the webpage without the need to alter the existing

Is there a way to align these two div side by side? <div class="main_one"> <div class="number_one">Title A</div> </div> <div class="main_two"> <div class="number_two">Title B</div> </div> <div class=" ...

Changing the dataURL of jqGrid dynamically after loading the Edit Form

Currently, I am working with jqGrid version 4.15.6-pre, which is the free version of jqGrid. Within my edit form, I have two dropdown lists that are being populated from the server using setColProp in the onSelectRow function. My objective is to reload t ...

The MUI text input element fails to correctly update the component's state

I have a functioning app that utilizes various inputs. Initially, the dataset is populated with data from an API request as shown below: const [userData, setuserData] = useState([]) const companyuser = useSelector(state=>state.companyuser.currentU ...

Escape key does not close the modal dialogue box

I’ve customized the codrops slide & push menu (http://tympanus.net/codrops/2013/04/17/slide-and-push-menus/) to create an overlay on a webpage. Although it functions as intended, I’m struggling to implement a way to close it by pressing the escape ...

How can I filter an array by a nested property using Angular?

I need help with objects that have the following format: id: 1, name: MyObj properties: { owners: [ { name:owner1, location: loc1 }, { name:owner2, location: loc1 } ] } Each object can have a different number of owners. I' ...

Servlet-enhanced Turn-Based Gaming Experience

I am working on developing a turn-based game, similar to Checkers, using Servlets and JSP pages. I have set up a specific page with a newGame button that redirects players to the gamePage. This redirect sends one player to Black.jsp and the other to Red.js ...

Unveiling the method to fetch the emitted value from a child component and incorporate it into the parent component's return data in Vue

How can I retrieve the title value passed by the Topbar component and incorporate it into the data() return section? I attempted to create a method to pass the value, but was unsuccessful despite being able to successfully log the value in the parent file. ...

"Encountering an Issue with Storing Private Key as a String in NodeJS: Saving to .txt Results in Writing "[

Currently, I am attempting to save an EC key pair from the elliptic library as a string in a .txt file. However, when I do this, it ends up writing ""[object Object]"" to the file. UPDATE: Just wanted to note that the issue of turning the object ...

Looking to remove a row with php, html, and ajax?

Trying to remove a row from an HTML table has been my latest challenge while working with Materialize CSS. Here is what I have so far, where the ID corresponds to the employee ID: https://i.stack.imgur.com/rjwba.png Below is the code snippet: <?php ...