Pm Rivière
Pm Rivière

Reputation: 291

Get state variable from child component using React 16.8^ coding style

This question has already been asked but i cannot find an answer using hooks.

I need to read a state variable in the page that calls a component.

MyPage.js

import React from "react"
import MyComponent from "../components/MyComponent"

export default function MyPage() {
  console.log("Read stateVariable value here " + stateVariable) // produce error
  return (
      <MyComponent />
  )
}

MyComponent.js

import React, { useState } from "react"
import ExternalModule from "ExternalModule"

export default function MyComponent() {

const [stateVariable, setStateVariable] = useState(0))

 return (
    <div
      onClick={setStateVariable(stateVariable + 1)}
    >CLICK HERE
      <ExternalModule
        stateVariable={stateVariable}
      />
    </div>
  )

How to console.log stateVariable in MyPage?

Upvotes: 0

Views: 76

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42288

When you have multiple components that need to access a piece of state, you want that state to be owned by the highest-up component in the tree and passed down to the rest.

Move the useState call up to MyPage and pass both stateVariable and setStateVariable down to MyComponent as props.

export default function MyPage() {

    const [stateVariable, setStateVariable] = useState(0)

    console.log("Read stateVariable value here " + stateVariable)

    return (
        <MyComponent 
            stateVariable={stateVariable} 
            setStateVariable={setStateVariable} 
        />
    )
}

export default function MyComponent({ stateVariable, setStateVariable]) {
    return (
        <div
            onClick={setStateVariable(stateVariable + 1)}
        >CLICK HERE
            <ExternalModule
                stateVariable={stateVariable}
            />
        </div>
    )
}

Upvotes: 1

Related Questions