Export React.JS variable and use in other file

So what I want to do is take the input from the radio buttons (metric or imperial) from Forecast.js, use them in a function in Conditions.js to determine whether it's hot or cold. I've exported the variable unit from Forecast.js but when I try to use it in the clothes() function it doesn't work. I've tried everything I found online and I tried to understand but I'm new to Reactjs.

Conditions.js https://pastebin.com/RHbLuqZD

import { unit } from '../Forecast/Forecast.js';

function clothes(t) {
    if (unit === "metric") {
        if (Number('t') <= 20)
            return (<>
                <img src={Cold} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
            It's cold, dress accordingly!
            </>);
        else
            return (<>
                <img src={Hot} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
            It's Warm, dress accordingly!
            </>);
    }

    if (unit === "imperial") {
        if (Number('t') <= 70)
            return (<>
                <img src={Cold} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
            It's cold, dress accordingly!
            </>);
        else
            return (<>
                <img src={Hot} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
            It's Warm, dress accordingly!
            </>);
    }
}

Forecast.js https://pastebin.com/wcBu8bwA

export default Forecast;
export let unit = this.state.unit;

The reason it doesn't work could be because I didn't do the import and export properly or because I didn't use the imported variable properly.

Edit: As I specified I'm a beginner, I don't know a lot, what I want is to see how to solve the problem and then understand how to do it. I just need to understand the problem with my code, or an alternative.

Upvotes: 0

Views: 202

Answers (2)

Marcos Sandrini
Marcos Sandrini

Reputation: 450

This is not how the whole thing works. One state variable like unit in one component is not exportable like that.

There are mainly two things you can do:

  • one is pass this unit value to the Conditions.js as a prop and then pass it on to the clothes function (when using it, just like you pass the temperature value) to work with it;
  • another one is to have a state management tool like Redux, reactN or even use the React's built-in context. If you have need to use one of those only once it may not compensate the extra boilerplate, but it may be worth learning about them at least.

Upvotes: 1

Ccc
Ccc

Reputation: 11

  1. if('clothes' and 'Forecast' is a parent-child realationship)

    the 'unit' state, can be deliver by 'props'

function Parent(props){
const [unit,setUnit] = useState("")
return(
 <Child unit={unit}>
)
}
   
function Child(props){
  console.log(props.unit)
return(
<div/>
)
}

  1. else. you can learn about 'react-redux'

Upvotes: 1

Related Questions