Guide to looping through a JSON file in a React application

Seeking assistance with a basic issue.

I currently have an array. When I click on a specific link on the screen, I only want to display that person's page, showing their name rather than all of them at once.

Initially, the user page displays all users. However, I would like to navigate to a specific user's page when clicked. How can this be achieved?

The users are identified by userid, which may come in handy.

Below are the codes for both the Profile Page and Users Page:

const ProfilePage = () => {
  const { posts, users } = useContext(UserContext);

  return (
    <>
      {users.map((item, index) => {
        return (
          <>
            <h1>{item.name}</h1>
          </>
        );
      })}
    </>
  );
};
return (
    <>
      {users.map((item, index) => {
        return (
          <>
            <a href={`/profile/${item.username}`}>
              <List className={classes.root}>
                <ListItem alignItems="flex-start">
                  <ListItemAvatar>
                    <Avatar alt="Remy Sharp" />
                  </ListItemAvatar>
                  <ListItemText
                    primary={item.email}
                    secondary={
                      <React.Fragment>
                        <Typography
                          component="span"
                          variant="body2"
                          className={classes.inline}
                          color="textPrimary"
                        >
                          {item.name}
                        </Typography>
                        {<br />}
                        {item.username}
                      </React.Fragment>
                    }
                  />
                </ListItem>
                <Divider variant="inset" component="li" />
              </List>
            </a>
          </>
        );
      })}
    </>
  );

For images of the User Page and Profile Page, see below:

User Page image: https://i.sstatic.net/2CeFC.png

Profile Page image: (initially displaying multiple names instead of just one)

https://i.sstatic.net/249NF.png

Answer №1

const UserPage = () => {
  const { posts, users } = useContext(UserContext);

  const { username } = useParams();//Dynamic route for username. Example: <Route path="/user/:username">
  const filteredUsers = users.filter(item => item.username === username);//Filter users with the given username

  //To ensure uniqueness, consider using a dynamic ID in the URL instead of name
  //const { id } = useParams();
  //const filteredUsers = users.filter(item => item.id === id);

  return (
    <>
      {filteredUsers.map((item, index) => {
        return (
          <>
            <h1>{item.name}</h1>
          </>
        );
      })}
    </>
  );
};

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

The function cannot be applied to d[h] due to a TypeError

Having some trouble with my code here. I'm trying to set up routes to display a gif using CSS animation when the page is loading. The gif shows up initially, but then everything fades out and the gif remains on the page. Additionally, I'm getting ...

Create an array in JavaScript that represents a normal distribution based on the provided minimum, maximum, mean, and sample size

Consider the following scenario: min = 1 max = 5 Ave = 3 size = 5 At this stage, we have [1,?,?,?,5] How can I determine the missing numbers? (It's simple -> [1,2,3,4,5] - but how do I create a JavaScript function to return this array) ...

How can information be exchanged between PHP and JavaScript?

I am working on a concept to display a graph of someone's scores within a div element. The process involves a button that triggers the graph drawing function upon clicking. Additionally, there is a data retrieval function that retrieves information fr ...

Embedding HTML code in JavaScript

I am in the process of developing a karaoke-style website where I aim to incorporate HTML elements along with text. My intention is to introduce a break tag that will display certain lyrics on a separate page. You can access the codepen for this project h ...

Preventing the use of the <select> tag in JavaScript

As a beginner in JavaScript, I thought it would be a great idea to work on a simple Calculator project. I've already tackled the basics like addition and subtraction, but now I'm contemplating adding a squareroot function to it. The design incl ...

Clicking on the (x) button element will eliminate the DOM node from a list

https://i.stack.imgur.com/GxVYF.png A value is being dynamically added to my page, and here is the code snippet: function favJobs(data){ number_of_jobs_applied = data.total_bookmarked; $('.bookmark-title').append(number_of_jobs_applied, " ...

The JScolor Color Picker has a slight misalignment

I am having an issue with the jscolor color picker on my webpage. The rainbow part of it appears offset within the rest of the picker. You can see what it looks like on my site here: (https://ibb.co/9N8dHXs). On my website, I have a large canvas for three ...

Merge two lists to create a unified dictionary or output in the most concise manner

Two lists are available: a=[0,0.3,0.6] b=['x','y','z'] Combining the lists into a dictionary using zip allows for iteration (Note: the order of list 'a' changes when zipped). Seeking the shortest possible one-liner ...

What is the solution for fixing an error that says "There is no 'style' property on the 'Element' type"?

I'm struggling to fix an error in my JavaScript code. I created a script to display a tab indicator when a tab is clicked, but I keep getting the error message: "Property 'style' doesn't exist on type 'Element'". The tabs them ...

Generate HTML tags dynamically within a JSON document using PHP

Is there a way to incorporate HTML markups (generated dynamically by a CMS) into a JSON file? I am aware that in the html string, one must escape double quotes by adding "" as shown below. { "title": "Title", "da ...

Utilize Ajax to display detailed product information within a modal using Django

In my application, the main purpose is to showcase a collection of furniture items on the homepage. Each furniture item has a quick preview button that, when clicked, should display detailed information about that specific item. I attempted to integrate aj ...

Determining whether an element possesses an attribute labeled "name" that commences with a specific term, apart from the attribute "value"

I'm planning to use distinctive data attributes with a prefix like "data-mo-". Let's say I have the following elements: <span data-mo-top-fade-duration="600">Title 1</span> <span data-mo-bottom-fade-duration="600">Title 2</ ...

Is it possible to determine if <script> elements were included in the HTML source code or loaded in using another JavaScript script?

For instance, when I use the code below to retrieve a NodeList of all scripts on a webpage: document.querySelectorAll('script') Is there a method to distinguish between scripts that were part of the original HTML source and those that were added ...

Capture line breaks from textarea in a JavaScript variable with the use of PHP

I need help with handling line breaks in text content from a textarea. Currently, I am using PHP to assign the textarea content to a Javascript variable like this: var textareaContent = '<?php echo trim( $_POST['textarea'] ) ?>'; ...

What is the best way to extract data from this JSON in ASP.NET?

Json.Net is the library I am currently using. Can anyone provide guidance on how to properly parse the JSON data below in an ASP.Net environment? Any help is greatly appreciated. [ { "1":[ "Fax1", "Fax2", "Fax3" ] }, { "2":[ ...

Using Three.js to Spin Cylinder Towards a Vector3 Destination

I've attempted a thorough search, but unfortunately, I haven't come across any solutions that address my issue: I have a vector and a CylinderGeometry Mesh. My goal is to make the cylinder face the direction indicated by the vector. The input pa ...

What is the best way to reload (using F5) and navigate to a new page using AngularJS?

In my web application, there are two pages with forms: purchase1 and purchase2. If a customer refreshes the purchase2 page, I want them to be redirected back to purchase1. I've been struggling to achieve this by configuring a setup like: .config(fu ...

The utilization of ui-view resulted in an error message stating "Failed to instantiate the ui.router

Recently, I've been diving into Angularjs and attempting to organize this plunker by splitting it across different files using ui-view. Let's take a look at my app.js 'use strict'; angular.module('Main', []); angular.modul ...

Python does not display all JSON key values

Code: import json data = open('data.json', 'r') data = json.load(data) x = open('test.txt', 'w') for s in range(len(data)): print(data[s]["osm_id"]) x.write(str(data[s]["osm_id"]) + "\n") JSON: ...

Creating a high-performing JavaScript script using AJAX: Tips and Tricks

When it comes to structuring my JavaScript scripts, I often find myself following a similar pattern when dealing with AJAX or server responses. However, I don't believe this is the most efficient method. Is there a better approach for handling these t ...