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
install zustand
Create Store
import create from 'zustand'
const useArray = create((set) => ({ arrayVal: 0, setArray: () => set((state, value) => ({ array: value })) }))
To use it, in any component
const arrayVal = useArray((state) => state.arrayVal)
and there you have it.
Another Option is to use localStorage
To set the value
localStorage.setItem('data', JSON.stringify(val));
To get the value
JSON.parse(localStorage.getItem('data'));