While the answer above is valid, it's always good to write modular code and keep your react components stateless (without having state variables). The following code shows a better approach to your problem:

import React from "react";

import listUnitItem from "./listUnitItem.scss";

//Number formatting
const numeral = require('numeral');

export default class ListUnitItem extends React.Component {
    // Save this method in some Utils class where you can access from other components.
    getFormattedNumber(number){
        //format numbers greater than 1000
        if (number > 1000) {
            //only format number
            number = numeral(number).format('0.0a');
        }
        return number
    }

    render() {
        return(
            <li className="list-unit-item col-sm-2">
                <span className="unit-item-number">{this.getFormattedNumber(this.props.number)}</span>
                <span className="unit-item-title">{this.props.title}</span>
            </li>
        )
    }
}

I hope this helps!

Answer from Gui Herzog on Stack Overflow
🌐
Reddit
reddit.com › r/learnreactjs › why can't i access this variable outside its function? is it because of the useeffect?
r/learnreactjs on Reddit: Why can't I access this variable outside its function? Is it because of the useEffect?
September 22, 2022 -

I was looking at this tutorial (the part about not using let, var or const will make the variable available outside of the function and uses the variables Video and Length )

https://tutorial.eyehunts.com/js/how-to-access-variable-outside-function-in-javascript-code/

I get the error Cannot find name 'outside' like it wants me to declare outside first? In the example in the tutorial they don't declare it and it says it works.

Here is my code:

const Home: React.FC = () => {



  const printCurrentPosition = async () => {
    outside = await Geolocation.getCurrentPosition();
     

    console.log('Current position:', outside)

  }



  useEffect(() => {
    printCurrentPosition()

  }, [])

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Blank</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent fullscreen>
        <IonHeader collapse="condense">
          <IonToolbar>
            <IonTitle size="large">Blank</IonTitle>
          </IonToolbar>
        </IonHeader>
	  <IonText>
	    Hello {outside}
	  </IonText>
        <ExploreContainer />
      </IonContent>
    </IonPage>
  );
};

export default Home;

Top answer
1 of 2
29

I see two options here.

  1. Assign the variables to the window object
  2. Use environment variables

Using the window object

To use the window object, declare the variable as

myVar = 'someString'

or

window.myVar = 'someString'

In both cases you'll access the variable within React with window.myVar. Here's a quick example:

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, React and ES6!</h1>
        <p>Let's play. :)</p>
        <p>{window.myVar}</p>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));
html,
body {
  height: 100%;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: Helvetica Neue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>
<script>
  window.myVar = 'someString2'
</script>

Using environment variables

The Create React App build allows for environment variables to be used within the app. To add an environment variable create a .env file in the root of your project, then add the appropriate variables and prefix the variable name with REACT_APP_. For example:

REACT_APP_MYVAR = "someString"

In the app these variables can be accessed within your components with {process.env.REACT_APP_MYVAR}, or within the HTML with %REACT_APP_MYVAR%.

2 of 2
6

The EcmaScript 6 introduced block-scope variables and constants declared by let resp. const.

In contrast to the "old style" declaration of variable by var the visibility of such variable resp. constant is limited to actual block.

The scope of constant const1 (resp. const2) is therefore limited only to the code inside the script tag. To be able to access the const1 (resp. const2) from another script tag you would need to change its visibility. This can be achieved either by declaring it by var or by assigning its value to a variable declared by var.

E.g.:

<script type="text/javascript">
  const const1 = "1234";
  const const2 = "5678";
  var visibleConst1 = const1;
</script>

Later in your React application you can read it from window.visibleConst1.

🌐
Reddit
reddit.com › r/reactjs › [beginner question] accessing variables outside of exported class
r/reactjs on Reddit: [Beginner Question] Accessing variables outside of exported class
February 7, 2016 -

I have been using something like:

export default class SomeComponent extends Component { ... }
let size;
// or
const styling = { backgroundColor: 'rgb(0,0,0)' }

but the idea behind it seems a little vague to me. From what little I understand of scopes and closures I understand that both size and styling are considered globals, or at least within the file. When the file is exported I have assumed the globals are also attached to the module in some form or another, what is that form? What are the main differences between

import { styling } from './SomeComponent'

assuming I exported the const. Is it more private access? What value or should I ask what does 'let size' belong to if it is assigned a value within a component ?

Is there a difference than something like

setStyling() {
return {
  backgroundColor: 'rgb(0,0,0)'
}
}

// somewhere in the component

<div style={this.setStyling.bind(this)} />

or is this all syntactic sugar?

Top answer
1 of 2
1

If you export a variable you can import it into another file. So if you dont explicitly export it, it's private to the module it's defined in.

export const myVar; is public and can be imported

const myPrivateVar; is private and cannot be imported used directly or referenced in anyway.

2 of 2
1

From what little I understand of scopes and closures I understand that both size and styling are considered globals, or at least within the file.

The module is created by putting a closure around the file. Like (function(){ })(); Nothing within the file is strictly global. All of the variables are rewritten to look like var styling = {} and var size; So once the function closure is wrapped around them, they're tied to that scope alone.

Export basically hoists part of the code outside of the function. So it compiles to something like:

module = {}
module.exports.styling = { .... } 
(function(){})(module.exports.styling);

Assuming I exported the const. Is it more private access?

No now styling is part of the public interface of the module.

What value or should I ask what does 'let size' belong to if it is assigned a value within a component ?

What?

is this all syntactic sugar?

Yep. That's why you can cross compile it down to regular ES5 easily. If you have a language which begun with a non-class style, then classes/modules will always be syntactic sugar due to backwards compatibility. C++ basically does this.

If classes/modules were going to be 'real' parts of the AST, then it'd break backwards compatibility... and its really unnecessary to do so.

Top answer
1 of 1
9

You cant access variable outside the block. If you want to access then you need to declare all variable outside the block of useEffect. You can do it in multiple ways like below.

Method 1: Declare variable outside.

import React, { useEffect } from 'react';

const Warning: React.FC = () => {
  let confirm;
  let invalid;
  let confirmed;
  let warningBar;

  useEffect(() => {
    confirm = document.getElementById("confirm");
    invalid = document.getElementById("invalid");
    confirmed = document.getElementById("confirmed");
    warningBar = document.getElementById("warning-bar");
    printAll();
  }, []);

  function printAll () {
    console.log(confirm);
    console.log(invalid);
    console.log(confirmed);
    console.log(warningBar);
  }

  return (
    <div>
      <section className='warning-bar' id='warning-bar'>
        <div className='confirm' id='confirm'>Confirm</div>
        <div className='invalid' id='invalid'>Invalid</div>
        <div className='confirmed' id='confirmed'>Confirmed</div>
      </section>
    </div>
  );
};

Method 2: Using useRef

import React, { useEffect, useRef } from 'react';

const Warning: React.FC = () => {
  let confirm = useRef({});
  let invalid = useRef({});
  let confirmed = useRef({});
  let warningBar = useRef({});

  useEffect(() => {
    printAll()
  }, []);

  function printAll () {
    console.log(confirm.current);
    console.log(invalid.current);
    console.log(confirmed.current);
    console.log(warningBar.current);
  }

  return (
    <div>
      <section className='warning-bar' ref={warningBar} id='warning-bar'>
        <div className='confirm' ref={confirm} id='confirm'>Confirm</div>
        <div className='invalid' ref={invalid} id='invalid'>Invalid</div>
        <div className='confirmed' ref={confirmed} id='confirmed'>Confirmed</div>
      </section>
    </div>
  );
};

Demo Link

🌐
Team Treehouse
teamtreehouse.com › community › declaring-functions-and-variable-outside-class-react
declaring functions and variable outside class react (Example) | Treehouse Community
December 2, 2018 - this is the document page i was reading. https://reactjs.org/docs/lifting-state-up.html · Front End Web Development Techdegree Graduate 84,738 Points ... My guess is the reason they're not declared inside the class is that they don't have any reason to be in the class. For example this function: function toFahrenheit(celsius) { return (celsius * 9 / 5) + 32; } It takes it a celcius number and returns a fahrenheit number. This has nothing to do with React, and nothing to do with the component here.
🌐
YouTube
youtube.com › watch
Accessing a Variable Outside a Function in React JS: A Simple Solution - YouTube
Discover how to efficiently access variables defined within functions in React JS using `useState` and `useEffect`. This guide explains the process step-by-s...
Published   May 26, 2025
Views   0
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 49154492 › variable-accessible-outside-the-function
reactjs - Variable accessible outside the function - Stack Overflow
export default class RouterScreen extends React.Component { componentDidMount() { const { navigate } = this.props.navigation; fb.auth().onAuthStateChanged(user => { if (user) { // user exist var userRef = fb.database().ref('users/' + user.uid); userRef.once('value').then(snapshot => { var gameOfTheUser = snapshot.child('game').val(); console.log('0 : ' + gameOfTheUser); }); if (gameOfTheUser !== null) { // gameOfTheUser --> error variable is not created // user in game --> redirect to Game (@user, @game) console.log('InGame'); var gameID = gameOfTheUser; console.log('1 : ' + gameOfTheUser); console.log('1 : ' + gameID); navigate('Game', { user, gameID }); } else { // user not in game --> redirect vers Choose (@user) console.log('NotInGame'); navigate('Choose', { user }); } } else { // user doesn't exist navigate('Auth'); } }); }
🌐
Stack Overflow
stackoverflow.com › questions › 70742375 › how-can-i-access-a-variable-outside-of-a-function-in-reactnative
reactjs - How can I access a variable outside of a function in ReactNative? - Stack Overflow
if you are beginner then I will suggest you first understand basics React Native components and state management, but if you are comfortable with basic fundamentals the you can pass your values to another components using props and second method is using context APIs or other state management libraries/frameworks like React Redux etc, you can use following method to pass your values using props · const Settings = () => { ... <AnotherComponent isSwitchOn={isSwitchOn} themeSwitchOn={themeSwitchOn} /> ... } const AnotherComponent = ({isSwitchOn, themeSwitchOn}) => { ... // here you can access your props ... } ... This is not my problem, I have another function of which I'd like to change the settings from the "settings" function.
🌐
Anishaneinc
anishaneinc.com › wp-content › plugins › apikey › acceleration-logstash-studying › how-to-access-variable-outside-function-in-react.html
How to access variable outside function in react
React Hooks are a new addition in React 16. Also we are handling the initial state of the component for visibility and reference of the component to detect outside click. We have to make sure that the get () function is executed and completely finished before we can attempt to access any variable of the get () function.
🌐
Quora
quora.com › How-do-I-access-variables-outside-renders-defined-in-MAP-in-a-render-function
How to access variables outside renders defined in MAP() in a render function - Quora
Answer: One of the nice things about React (in my opinion) is that there isn’t any fancy templating magic to worry about in render functions. Render is just a normal JS function and map is just part of the Array prototype in JS, so you can just reference variables like you normally would ...
🌐
Stack Overflow
stackoverflow.com › questions › 67996468 › how-to-access-a-components-variable-outside-the-component-in-react-native
reactjs - How to access a component's variable , outside the component, in react native? - Stack Overflow
There are two ways to achieve this. First is to lift your state up to the parent component S where you functions that operate on the said state reside. This is the most common thing to do in React world.
🌐
Stack Overflow
stackoverflow.com › questions › 41992983 › react-how-to-make-local-variable-accessible-outside-the-class
reactjs - REACT - how to make local variable accessible outside the class - Stack Overflow
February 2, 2017 - i got a problem in making my local variable to be accessible outside the class class LoginForm extends React.Component { constructor(props) { super(props); } render() { const { ...
🌐
Stack Overflow
stackoverflow.com › questions › 46011686 › sending-a-variable-outside-a-function-to-another-function-in-react
reactjs - Sending a variable outside a function to another function in react - Stack Overflow
If all you wanted to do was something simple, like logging, what you've done is fine. However if you want to do more than that, your best bet is to write the method outside of the render component and pass it into the OnPlaceSelected function.
Top answer
1 of 3
3

TodoComponent

import React from 'react';
import ReactDom from 'react-dom';
import TodoItem from './todoItem'; 

class TodoComponent extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        todos: ["clean up", "walk doggo", "take nap"]
      };
    }
    handleDelete(item){
        let todos = this.state.todos;
        todos= todos.filter((todo) => todo !== item);
        this.setState((prevState) => ({
            todos: todos
        }));
    };
    render() {

      return (<div>

        <h1>The todo list:</h1>
        <ul>
          <TodoItem todos={this.state.todos} handleDelete={this.handleDelete}/>
        </ul>
      </div>);
    }

  }

  ReactDom.render(<TodoComponent/>, document.querySelector(".todo-wrapper"));

Todo Item

import React from 'react';
import ReactDom from 'react-dom';

export default class TodoItem extends React.Component {
    render() {
        return ( 
            this.props.todos.map((item) => {
            return (
                <li>
                    <div className="todo-item">
                    <span className="item-name">{item}</span>
                    <span className="item-remove" onClick={() => this.props.handleDelete(item)}> x </span>
                    </div>
                </li>
            )
        }))
    }
}

Your code is having the problem in TodoItem that you are trying to delete items in TodoItem where you do not have access to state. And moreover If you do some actions in component and you want to get the change reflected the your components must re render. And this is possible when your state is changed. And component related to corresponding changes will re render itself

2 of 3
1

I have not tested it so there might be some typos but you have to do it like this

import React from 'react';
import ReactDom from 'react-dom';

export default class TodoItem extends React.Component {

handleDelete(item){
   this.props.updateTodos(item)
};

render() {
//Add all this.props items
 let todos = this.props.todos;
 todos = todos.map((item, index) => {

  return (
  <li>
    <div className="todo-item">
      <span className="item-name">{item}</span>
      <span className="item-remove" onClick={this.handleDelete.bind(this, item)}> x </span>
    </div>
  </li>);
 });


 return (<React.Fragment>{todos}</React.Fragment>)
};
}



import React from 'react';
import ReactDom from 'react-dom';
import TodoItem from './todoItem'; 

class TodoComponent extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    todos: ["clean up", "walk doggo", "take nap"]
  };
  this.updateTodos =this.updateTodos.bind(this);
}
 updateTodos(item){
   this.setState({todos :this.state.todos.filter((val,index) => {
     return item !== val;
   })})
}
render() {

  return (<div>

    <h1>The todo list:</h1>
    <ul>
      <TodoItem todos={this.state.todos} updateTodos ={this.updateTodos}/>
    </ul>
  </div>);
}

}

 ReactDom.render(<TodoComponent/>, document.querySelector(".todo-wrapper"));