Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React component pass a const string to another component

I have a component that concatenates several strings into one string, which I declare as a const to use as a URL. How to I use this const in another component, which needs the URL to fetch data?

Example of the code:

URLconcatenate.js creates the const URLstring

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const string01 = 'www.'
const string02 = 'apple';
const string03 = '.com'
const urlString = string01 + string02 + string03

//this validates the concatenation
console.log(urlString);

function URLconcatenate() {
    return (
        <div>
            {urlString}
        </div>
    )
}

export default URLconcatenate

Datafetch.js (needs to receive and use the const urlString

import { useState, useEffect } from 'react';
import URLconcatenate from './URLconcatenate';

const Datafetch = () => {
    const [price, setPrice] = useState([]);
    useEffect(() => {
        fetch(urlString)
            .then((response) => {
                return response.json();
            })
            .then((data) => {
                console.log(data);
                setPrice([data]);
            });
    }, []);
    return (
        <div>
            {price.map((thePrice) => (
                <p key={thePrice.c}>Today's price for AAPL is: ${thePrice.c}</p>
            ))
            }
        </div >

    );
};

export default Datafetch 

>Solution :

Make sure to export your urlString

// URLconcatenate.js
export const urlString = string01 + string02 + string03


// Datafetch.js
import { urlString } from './URLconcatenate';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading