3

I have a variable in a component. And I want to be able to access this variable in another component. I use NextJS.

How can I do ?

code :

Component/Question.js

import { useState } from "react";

function Questions() {

    const [question, setQuestion] = useState("")

    const handleChange = event => {
        const target = event.target
        const name = target.name
        const value = target.value
        setQuestion(value)
    }
    ...

pages/jeux/test.js

const Game = (index) => {
   // I want have acces at the 'question' variable
   //console.log(question)

   return (
       <div>
           <p className="text-white">{index.index.title}</p>
       </div>
   )
}
2
  • You can also use Router useRouter, you have all props of each prop of each compnent Commented Jan 20, 2022 at 13:39
  • Have you got an example plz ? Commented Jan 20, 2022 at 15:24

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Huge overkill for such a simple task.
thank you for your help, im gonna use ReactContext I think
0

as react just send your variable through props

const passTheData = {}

<YourComponent data={passTheData} />

then in you component:

function YourComponent({data}){
  console.log(data)
}

2 Comments

Huum okey, but With my code, where I put the information ?
```js const Game = ({index, question})=>{ // do ce que tu veux avec la question }
0
import React, {useState} from "react"

const Game = ({theBigQuestion}) =>{
  console.log(theBigQuestion)
}

const Question = () =>{
  const [question, setQuestion] = useState("")
  const theQuestion = "C'est quoi la couleur de ton slip?"
  const handleChange = ()=>{
    setQuestion(theQuestion)
  }

  return (
    <Game theBigQuestion={question} />
  )
}

something like that

3 Comments

If I do that, i can use it just in 1 file, no ?
But in my example, the variable theBigQuestion will be available only in the Game component. if you want to pass it to other places you better use useContext or just call the component and pass it the same variable and so on
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.