Search code examples
javascriptreactjscomponents

Import Variable from React Component to Javascript File


I have a react component Button in which I have two states name and players. I want to import these states into another JS file. This file is a vanilla javascript file and not a component.

Here are the codes:

Button.js

import {useState} from "react"

import {buttonContent} from '../buttonContent'
import {correctAnswer} from "../pageTraversal"
import {verifyResults} from "../verifyResults"

const Button = ({textInput, updateApp, updatePage, updateError}) => {
  const [pageTitle, updateButton] = useState("home-page")
  const [textVisible, textVisibility] = useState("")
  const [disabled, changeClick] = useState(false)
  const [cursor, changeCursor] = useState("pointer")
  const [name, updateName] = useState('')
  const [players, updateFriends] = useState('')

  const startPages = ["home-page", "welcome", "scenario", "the-adventure-begins"]

  const navigatePage = () => {
    if (startPages.includes(pageTitle)){
      changeCorrectPage()
      return
    }

    if(textInput===""){
      updateError("")
      return
    }
    else{
      updateError("remove")
    }

    const response = verifyResults(pageTitle, textInput)
    if (pageTitle === "instructions"){
      updateName(response["player"])
      updateFriends(response["friends"])
      changeCorrectPage()
    }

    if(response === "correct"){
      changeCorrectPage()
    }
  }

  const changeCorrectPage = () => {
    const page = correctAnswer[pageTitle]
    updateApp(page)
    updatePage(page)
    changeButton(page)
  }

  const changeButton = (page) => {
    textVisibility("hide")
    changeClick(true)
    changeCursor("auto")
    setTimeout(() => {
      updateButton(page)
    }, 2500)
    setTimeout(() => {
      textVisibility("show")
    }, 4500)
    setTimeout(() => {
      changeClick(false)
      changeCursor("pointer")
    }, 6500)
  }

  return (
    <div>
      <button className={`button mx-auto`}
        id={(pageTitle==="home-page" ? "home-button" : "")}
        style={{
          "cursor": {cursor},
        }}
        disabled={disabled}
        onClick={navigatePage}
      >
        <h1 className={`button-text ${textVisible}`}>
          {buttonContent[pageTitle]}
        </h1>
      </button>
      <Players name={name} friends={friends} />
    </div>
  )
}

export default Button

I want to import the two states name and players into another javascript file below where I want to use them as normal variables.

const width = window.innerWidth;
const height = window.innerHeight;
let textSize = ''
if(height > width){
  textSize = "small"
}
console.log(name)
console.log(players)

I have tried importing the variables as normal variables, but that doesn't work here. Please suggest a suitable way of doing this.


Solution

  • There is no official approach for this link of problem. But I suggest to use browser storages like localStorage to handle this.

    So:

    1) Save the states on localStorage based on their changes with useEffect()

    useEffect(()=>{
        localStorage.setItem("name", name);
        localStorage.setItem("players", players);
    },[name,players])
    

    2) Get the states data with localStorage everywhere that you want

    const width = window.innerWidth;
    const height = window.innerHeight;
    let textSize = ''
    if(height > width){
      textSize = "small"
    }
    console.log(localStorage.getItem("name"))
    console.log(localStorage.getItem("players"))