-2

I am a little new on react. How can I pass a variable with its value from one react js file to another?

File A.js:

const [value, setValue] = useState(35)  

File B.js:

import value from "./A.js"
console.log(value)
Anthon Santhez
  • 402
  • 1
  • 7
  • 13

2 Answers2

1

You have to export it either as a default or a regular export.

Try the following:

export const ...

or:

export default const ...
DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127
Arcanus
  • 642
  • 5
  • 20
  • When I write export const, error says: Modifiers cannot appear here.ts(1184) – Anthon Santhez Mar 16 '22 at 18:10
  • And when I write outside of my main component(top-level comp), I mean: "export const [value, setValue] = useState("10")" error comes: "invalid hood call. Hooks can only be called inside of the body of a function..." error. It seems I cannot use useState outside of my main comp – Anthon Santhez Mar 16 '22 at 18:13
  • You can pass setState as a prop to a child component. You can't export it. – Arcanus Mar 16 '22 at 18:27
  • so how can I export a "variable" to a different file? Probably using useState since it is a variable. – Anthon Santhez Mar 16 '22 at 18:33
  • Where do you need this variable? This is how you pass state as a prop. https://stackoverflow.com/questions/56028635/passing-usestate-as-props-in-typescript – Arcanus Mar 16 '22 at 18:37
  • I am now trying to understand it. I didn't think exporting a variable is such complicated. – Anthon Santhez Mar 16 '22 at 18:53
  • meanwhile, I don't need to update the value in the B file, I will just use the state of it in A file – Anthon Santhez Mar 16 '22 at 19:00
0

In file a.js // source file

Add this:

export const endpoint_val = 'value of endpoint';

Go to file b.js

import { endpoint_val } from './a.js'
Jakub Kurdziel
  • 3,216
  • 2
  • 12
  • 22
Olive
  • 11
  • 2