Quick Help Needed! I have Two React components Vendors and VendorsList. In Vendors.js Component i have asset.asset_name text rendered in table format. What I want is, When I click on I asset.asset_name, I wanted to pass it’s value from Vendors component to VendorsList component. How could I do this?
Here is code for Two Components
Vendors.js
import React, { useEffect, useState } from "react"; import { axios } from "axios"; const Vendors = () => { const [data, setData] = useState({}); const baseURL = "http://127.0.0.1:8000/api/business_process/business-impact/business-assets-detail"; useEffect(() => { axios .get(baseURL) .then((response) => { setData(response.data); }) .then( (response) => {}, (err) => { alert("No Data To Show"); } ) .catch((err) => { return false; }); }, []); const DisplayData = data.business_assets?.map((asset) => { return ( <tr> <td>{asset.business_assets}</td> <td onClick={() => alert(asset.asset_name)}>{asset.asset_name}</td> </tr> ); }); return <div></div>; }; export default Vendors;
Here is VendorsList.js
import React from "react"; const VendorsList = () => { return ( <div> <h1>{foo}</h1> </div> ); }; export default VendorsList;
I need asset.asset_name value to be passed to VendorsList when I click on asset.asset_name value from Vendors component
Advertisement
Answer
I don’t think you’re passing the asset_name
into your VendorsList
component at all. I think the quickest way is to directly render the VendorsList
in your Vendors
component by putting it in the return of your Vendors
component. You would also need something to record what you have clicked so you can use another useState
for this. Below is how you’d achieve this:
Modify your Vendor.js
to look like this:
import React, { useEffect, useState } from "react"; import { axios } from "axios"; import VendorsList from '<path to your VendorList component>' const Vendors = () => { const [data, setData] = useState({}); const [clickedAsset, setClickedAsset] = useState() const baseURL = "http://127.0.0.1:8000/api/business_process/business-impact/business-assets-detail"; useEffect(() => { axios .get(baseURL) .then((response) => { setData(response.data); }) .then( (response) => {}, (err) => { alert("No Data To Show"); } ) .catch((err) => { return false; }); }, []); const DisplayData = data.business_assets?.map((asset) => { return ( <tr> <td>{asset.business_assets}</td> <td onClick={() => setClickedAsset(asset.asset_name)}>{asset.asset_name}</td> </tr> ); }); return ( <div> <DisplayData/> <VendorList clickedAssetName={clickedAsset}/> </div> ); }; export default Vendors;
Then to use the clickedAssetName
that you just passed, access it like this in your VendorsList.js
component:
import React from "react"; const VendorsList = ({clickedAssetName}) => { return ( <div> <h1>{clickedAssetName}</h1> </div> ); }; export default VendorsList;