Home > Software engineering >  I want to make my array global in reactjs
I want to make my array global in reactjs

Time:09-28

How can I make my infoArray global so that I can access it from anywhere just by importing and data also remain in it while information is given to it on different pages.

Can you tell me how to declare it in this file

import React from 'react'
import { Link } from 'react-router-dom'
export default function Menu(props) {
  
  const infoarray = [] ; 
  return (
    <div>
      <div className="location sample">
        <i ></i>
        We operate in NOIDA and DELHI only.
        {/* window.open("/insert/your/path/here"); */}
      </div>
        <div className="go" >
          <Link to="/cart"> 
            <i />
              </Link>
            <div className="text">
              Go to cart
            </div>
        </div>

      <hr className="line" />
      {/* <hr className="line" /> */}
      <div className="about-us">
        You can share your designs on WhatsApp
        <i ></i>
        <a href="https://wa.me/<919650988301>" target='_blank' rel="noreferrer" className='no'>9650988301</a>
        we can make the same on the cake.
      </div>
    </div>
  )
}

// export  infoArray ; 

CodePudding user response:

In this file you can define the array before exporting the default function like this:

const infoarray = []; 
export default function Menu(props) {}

Or

You can declare a global context variable in any of the parent components and this variable will be accessible across the component tree by this.context.varname. Just specify childContextTypes and getChildContext in the parent component and after that you can use/modify this from any component by just specifying contextTypes in the child component.

CodePudding user response:

The simple way is to use Store forexample Zustand is very simple

Steps

  1. install zustand

  2. Create Store

    import create from 'zustand'

    const useArray = create((set) => ({ arrayVal: 0, setArray: () => set((state, value) => ({ array: value })) }))

  3. To use it, in any component

    const arrayVal = useArray((state) => state.arrayVal)

  4. and there you have it.

Another Option is to use localStorage

  1. To set the value

    localStorage.setItem('data', JSON.stringify(val));

  2. To get the value

    JSON.parse(localStorage.getItem('data'));

  • Related