You need to use a global state management such as Redux (or Redux Toolkit!), or use React Context to share the variable.
I'm more familiar with redux toolkit (abbreviated as RTK). in RTK, you need to create a slice to manage a particular set of states.
For example lets assume your questions are for a quiz app, so using RTK, you can create a quiz slice like this
quizSlize.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
questions: [] // your initial questions
};
const quizSlice = createSlice({
name: "quiz",
initialState // this is equal to initialState: initialState,
reducers: { // reducers are functions to mutate the state
resetState: () => initialState,
setQuestions: (state, action) => {
state.questions = action.payload
},
},
});
export const _quiz = quizSlice.actions; //_quiz will be the object that stores all your reducers
export const $quiz = ({ quiz }) => quiz; //$quiz will be the object that stores all your variables
export default quizSlice.reducer;
after creating the slice you can use them in any component (after setting it up in the app of course)
using your example:
import {useDispatch, useSelector} from 'react-redux'
import {$quiz, _quiz} from './quizSlice'
function Questions() {
const dispatch = useDispatch() // this is used to call the reducer
const {question} = useState($quiz) // your variable
const handleChange = event => {
const target = event.target
const name = target.name
const value = target.value
dispatch(_quiz.setQuestion(value))
}
...
import {useSelector} from 'react-redux'
import {$quiz} from './quizSlice'
const Game = (index) => {
// I want have acces at the 'question' variable
const {question} = useSelector($quiz) // your variable
//console.log(question)
return (
<div>
<p className="text-white">{index.index.title}</p>
</div>
)
}
Hope this helps. for how to setup the RTK in your app, you can head to Redux toolkit on how to set it up, or find example apps
RouteruseRouter, you have all props of each prop of each compnent