Passing data between multiple components in ReactJs by utilizing the Id field

Is there a way to transfer data from the Main Component to a child component based on the record Id? I have an index.js and detail.js pages set up. On the index page, I include a link like this: <Link to={{ pathname:/cards/${results.id}, state: results }} className={card-wrapper restore-${results.id}

}> {results.first_name} </Link>
. My goal is for the data associated with that particular record /Id value of the link to be sent to the detail page upon clicking the link, and then displayed.

Answer №1

After reviewing your code, I have identified 2 necessary changes: Firstly, in your index.js file, you should update the link's "to" property as follows:

to={{ pathname: `/cards/${results.id}`, state: results }}

Secondly, in your details.js file, modify the render function like so:

render() {
    const id = this.props.match.params.id;
    const data = cardData.data.Table.find(item => item.id === id)
    return (
      // Card details component
      <div className="card-details">
        <h2>{data.first_name}</h2>
        <h2>{data.id}</h2>

        <Link
          to={{
            pathname: "/",
            state: this.props.location.state
          }}
        >
          <button>Return to list</button>
        </Link>
      </div>
    );
  }

It is important to note that in the Link element, you are directing to /cards/${results.id}, where the id corresponds to the record from the database.

Furthermore, in details.js, you are extracting and utilizing the data associated with the id parameter from the table.

The errors in your code were:

  1. In index.js, the link was pointing to /cards/${results.index}, but results.index was undefined.
  2. In details.js, the way you referenced the data was incorrect, for instance:

cardData.data.Table[id].first_name

Remember that cardData.data.Table consists of an array of objects, where the ids are properties. Accessing cardData.data.Table[id] would only retrieve data for an id if that array contained sufficient objects up to that id value.

Answer №2

When working with this scenario, you have the option to pass the cardData.data.Table data as props and retrieve the ID from the router using .....params.id.

After that, you can update cardData.data.Table[0] with cardData.data.Table[i].

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

Transmit information to Flask server using an AJAX POST call

I'm completely new to Ajax requests. I'm trying to send data from a webpage to my Flask backend using an Ajax request, but I can't get anything to show up in the backend: Here is the request code I am using: function confirm() { cons ...

Adjust the size of a Div/Element in real-time using a randomly calculated number

Currently, I am working on a script that is designed to change the dimensions of a div element when a button on the page is clicked. The JavaScript function connected to this button should generate a random number between 1 and 1000, setting it as both the ...

Utilizing HTML and JavaScript to dynamically switch stylesheets based on the width of

When it comes to using stylesheets for mobile and non-mobile devices, there is a need for different approaches. The idea of comparing browser height and width in JavaScript seems like a good one, but the implementation may not always work as expected. ...

Leveraging ajax data to enhance visual representation in graphs

Having trouble fetching data from a database to display it in a graph.js graph. I've attempted setting a timeout for the async callback from Ajax, but nothing seems to be working. Any suggestions on how to make this work would be greatly appreciated! ...

Can you explain the distinction between using <router-view/> and <router-view></router-view>?

In various projects, I have encountered both of these. Are they just "syntactic sugar" or do they hold unique distinctions? ...

Deactivate one select box depending on the value chosen in another select box

I am looking to disable one select box when the other select box equals 1, and vice versa. While I know how to achieve this with IDs, the challenge arises as the select boxes I want to target have dynamically generated IDs and names via PHP. Therefore, I n ...

Utilize $stateParams to dynamically generate a title

When I click a link to our 'count' page, I can pass a router parameter with the following code: $state.go('count', {targetName: object.name}) The router is set up to recognize this parameter in the URL: url: '/count/:targetName& ...

Discovering the presence of a component in Angular 1.5

Link to embedded content $injector.has('myMessageDirective') is returning true, while $injector.has('myMessageComponent') is not. Has anyone else encountered this issue or found a solution? I am concerned that my components may not be ...

Issue with Vuejs where changes are made to the parent array, but the child component does not detect those

I'm facing an issue where my parent component has the following code: {{ fencing }} <FencingTable v-if="fencing.length > 0" :fencing="fencing" :facility="facility" /> get fencing() { return this.$sto ...

Hidden Password Field Option in HTML

My HTML password textbox has the input type set as password, but I can still see what is being typed. This shouldn't happen as password inputs should be masked. Can someone please advise me on how to resolve this issue? To replicate, copy the code be ...

Exploring the possibilities of integrating Storybook/vue with SCSS

After creating a project with vue create and installing Storybook, everything was running smoothly. However, as soon as I added SCSS to one of the components, I encountered the following error: Module parse failed: Unexpected token (14:0) File was process ...

Ways to implement form validation with JavaScript

I'm currently working on a project for my digital class and I'm facing an issue with my booking form. I have two functions that need to execute when a button is clicked - one function validates the form to ensure all necessary fields are filled o ...

What is the best way to prioritize a non-submit button over a submit button in material-ui?

I am facing an issue with a form on my website. Whenever I press the enter key, the form is automatically submitted. Everything seems to be working fine so far. However, there is a specific scenario where if a user selects a certain option in the form, it ...

Using JavaScript to shift an image sideways upon clicking a hyperlink on the page

One of my clients has a unique request for an image to move across the page from left to right when a link is clicked. I'm not very experienced with javascript, so I would really appreciate any guidance on how to make this happen. Thank you in advanc ...

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

Having difficulty in dynamically loading an image from an API's URL in Angular

In the title, I mentioned that I am utilizing a free API to display cryptocurrency news for my practice project. Everything seems to be working fine except for displaying the images in card view. I will share my code here, so if you have any suggestions on ...

What are the steps to utilize the feature of "nprogress"?

After successfully installing npm install nprogress in my project, I encountered an issue when trying to refresh the page - the console displayed the following message: hot-dev-client.js:182 [Fast Refresh] done hot-dev-client.js:196 [Fast Refresh] rebuildi ...

PHP code to display "ed elements that do not adjust height"

A php script is being utilized to scan a directory and populate a gallery with all the images. Within the <div id="content"> tag, the function <?php create_gallery("path"); ?> loads all the images. The issue arises when the height of the <d ...

Angular JS: Saving information with a promise

One dilemma I am facing is figuring out where to store data that needs to be accessed in the final callbacks for an http request. In jQuery, I could easily handle this by doing the following: var token = $.get('/some-url', {}, someCallback); tok ...

Discovering the source of a request payload

Is it possible for me to locate the source of a single item in the request payload using Chrome DevTools, even though I am unsure how it was created? Is there any way for me to find this information? ...