Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a global variable that can be accessed in different component in React?

Tags:

reactjs

I am getting username from server and i want to use the same user name from some other component. I know session Storage is one of the way to deal with it but i dont want to use for security reason. How can we create a global object in react?

like image 466
Rahul Avatar asked Nov 28 '18 01:11

Rahul


4 Answers

// most simplistic
window.myAppData = {
  userName: 'chad123',
  language: 'EN',
  // other stuff
};

window.myAppData.userName // 'chad123'

But most apps require something a bit more complex. You could use React context.

https://reactjs.org/docs/context.html


Context provider

// create context provider and consumer
const UserContext = React.createContext();
export default UserContext;
// wrap part of your app (or whole app) 
// with Provider that needs access to user
class App extends React.Component {
  constructor() {
    super();
    this.state = {
       user: null  
    };
  }

  componentDidMount() {
    yourUserAPI().then(user => this.setState({ user }));
  }

  render() {
    return (
      <UserContext.Provider value={this.state.user}>
        <MyComponent />
      </UserContext.Provider>
    );
  }
}

Context consumer

A) Current standard

// use anywhere in your app like this
// PS! must be descendant of Provider
class MyComponent extends React.Component {
  render() {
    return (
      <UserContext.Consumer>
        {user => {
          // do stuff with 'user'
        }}
      </UserContext.Consumer>
    );
  }
}

B) React Hooks (IN ALPHA)

// only works with functional 
// components (no classes)
function MyComponent() {
  const user = React.useContext(UserContext.Consumer);
  // do stuff with 'user'
  return 'something';
}
like image 119
Solo Avatar answered Nov 08 '22 08:11

Solo


I think to achieve that you need to use "React's context API"

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.

// Context lets us pass a value deep into the component tree
// without explicitly threading it through every component.
// Create a context for the current theme (with "light" as the default).
const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    // Use a Provider to pass the current theme to the tree below.
    // Any component can read it, no matter how deep it is.
    // In this example, we're passing "dark" as the current value.
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

// A component in the middle doesn't have to
// pass the theme down explicitly anymore.
function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

class ThemedButton extends React.Component {
  // Assign a contextType to read the current theme context.
  // React will find the closest theme Provider above and use its value.
  // In this example, the current theme is "dark".
  static contextType = ThemeContext;
  render() {
    return <Button theme={this.context} />;
  }
}

For further info do visit the link React context api

like image 34
Vijay Singh Avatar answered Nov 08 '22 08:11

Vijay Singh


You need a global state management like Redux.

Once you have this setup you can map your global state to your local component props and access it like you do any other prop: this.props.globalUsername.

I recommend you learn Redux by following their example program on the official website https://redux.js.org/basics/exampletodolist

like image 39
Shawn Andrews Avatar answered Nov 08 '22 09:11

Shawn Andrews


Well you can create a global variable in ReactJS but it doesn't make it more "secure" over Session/Local storage.

I think creating a global variable in React project is not the best practice at all because of this simply reason: Should components track down this variable for any change ? If the answer is yes, what you are looking at should be "How to manage global state in React" not "How to create a Global Variable in React".

You can achieve it with Redux. As official documentation says "Redux is a predictable state container" but you can think it as Global State Container for your app.

You can check redux out from that url: https://redux.js.org/

like image 1
aprogrammer Avatar answered Nov 08 '22 10:11

aprogrammer