Utilizing State Value beyond the Scope of a Function in React JS

I have 2 files, Header and App. App is my parent file and header is the child. I have designed a button in the header to open and close the sidebar, but I am unable to do that. My question is how to pass the state value from the header to the App file. Here's the code

import Header from 'components/Header';
import FirstSection from 'components/FirstSection';
import SecondSection from 'components/SecondSection';
import ThirdSection from 'components/ThirdSection';
import FourthSection from 'components/FourthSection';
import Sidebar from 'components/Sidebar';
import toggleState from 'components/Header';
function App(props) {
  return (
    <div className="">
      <Header setToggleState={toggleState}/>

      <div className="row mlr0 w-100">

    <div className={`pl-0 a ${toggleState ? 'col-md-3': 'd-none'}`} id="showOnClick">
<Sidebar />
</div>
<div className="col-md-9" id="fullScreen">
<FirstSection/>
<SecondSection/>
<ThirdSection/>
<FourthSection/>
 <div className="row justify-content-center">
  <img src={require("./images/Aqomi_Logo_Pink_Web_Small.png")} className="pb17"/>
</div> 
  </div>
  </div>
  </div>
  );
}

export default App;

App.js

import React, { useState } from "react";
import App from './../App';

export default function Header(props){
  const [toggleState, setToggleState] = useState(true);

  function changeClass(){

   setToggleState(!toggleState);

  }
    return(
        <div>
             <li className="nav-item"><a className="navbar-brand pl-1 hm "  onClick={changeClass}> 
             <img src={require("./../images/line.png")} height="23px" className={toggleState.className} />
               </a></li>


        </div>
        )
} 

Header.js

Answer №1

To achieve this, make sure to define toggleState and setToggleState in the App component first. Then, pass both of them as props to the Header component.

// Inside the App component
const [toggleState, setToggleState] = useState(true);

render() {
  return <Header toggleState={toggleState} setToggleState={setToggleState} />
}


// Inside the Header component
function Header(props) {
// Accessing the toggleState value
const { toggleState } = props

// Calling the setToggleState function
props.setToggleState(toggleState)

...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I efficiently create a suffix using this JavaScript code?

Take note that the code displayed below showcases the array in the console, rather than in the snippet output var names = ["maria", "mary", "marks", "michael"]; function add_suffix(names) { var suffixes = []; for (var i = 0; i < names.length; i+ ...

Store the value returned from either the URI or the response in the test context using Cypress IO

I am struggling to figure out how to extract a specific portion of a key from both the URL and the xhr response. I initially attempted using the URI method but couldn't specify to save only part of the value. .url().then(($url) => { co ...

React and SASS - issue with checkbox component not being properly aligned with its label

I'm brand new to React and I'm currently in the process of converting a pure HTML page into a React component. How can I adjust the SASS stylesheet to match the original HTML layout? Here is my current React setup (the checkbox displays on the r ...

The function addView is not recognized by Framework7

I am embarking on the journey of creating a Cordova app with Framework7 as my UI framework. My goal is to adopt inline pages as the architectural layout, but I am encountering an error in the console during project setup: An error message of "Uncaught Typ ...

Generating interactive buttons on the fly with React Native

Is there a way to dynamically create a checkbox based on API data and then incorporate it into my render function? I tried using forEach, but the data doesn't seem to be passed correctly, resulting in an error message: forEach is undefined. Here&apo ...

What is the best way to elegantly finish a live CSS animation when hovering?

Currently, I am working on a planet orbit code where I want to enhance the animation speed upon hover. The goal is for the animation to complete one final cycle at the new speed and then come to a stop. I have been successful in increasing the speed on hov ...

Navigating through files beyond the starting point

In the process of constructing a React seed project, I have organized the structure as follows: project │ package.json │ webpack.config.js │ .babelrc │ └───bin │ app.bundle.js │ └───node_modules | └─── ...

Tips for submitting a jQuery star rating:

I recently installed and added a plugin to one of my pages that transforms radio buttons into stars. While the form control works perfectly, I am facing an issue with submitting the form. The radio buttons are grouped together as stars but they do not subm ...

ways to trigger an event and pass it to a JavaScript function using a hyperlink

This specific "href="javascript:stop(this);" pattern allows the hyperlink object to be passed to the stop function. However, I also need to pass the invoked event to that function. How can I achieve this? Since my records are loaded through AJAX, I am unab ...

Could offering a Promise as a module's export be considered a legitimate approach for asynchronous initialization in a Node.js environment?

I am in the process of developing modules that will load data once and create an interface for accessing that data. I am interested in implementing asynchronous loading of the data, especially since my application already utilizes promises. Is it considere ...

Displaying JSON data in a browser using Node.js without the need for refreshing the page

I am currently working on a node.js server that fetches JSON data from an external source and displays it in a browser window. I need assistance in setting up an automatic update every minute to reflect any changes in the JSON without requiring a manual re ...

Set meanmenu to a fixed position

I am currently utilizing the meanmenu plugin to create a responsive menu for mobile devices. My goal is to fix the position of the menu at the bottom of the page so that users can easily access it. However, when I set the position of the meancontainer to ...

Tips for crafting HTML emails that avoid users inadvertently selecting extra spaces while copying and pasting

There is an email that I send out with a specific string that needs to be copied and pasted only once. The issue arises when users copy the string from Outlook as they tend to unintentionally include an extra space at the end of it. Although I understand ...

Ways to implement functional component in ReactJs

I am currently working with Reactjs and utilizing the Nextjs framework. In my project, I am attempting to retrieve data from a database using Nextjs. However, I am encountering an error that states "TypeError: Cannot read property 'id' of undefin ...

SignalR does not include cookies in the connection request

While working on a web application using ASP.NET Web API and SignalR, I encountered an issue that is proving to be quite challenging despite my understanding of HTTP. Currently, I have successfully set a cookie on all AJAX requests to the API, and subsequ ...

Looking to display the view source of an HTML page, but it keeps redirecting to another site when I try. Anyone know how to diagnose and fix this issue?

Can anyone assist me in displaying the HTML source of a page without it redirecting to another site? Here is the URL: ...

Utilizing an AngularJS factory to invoke a function within another function

I am encountering an issue with my AngularJS factory that consists of multiple functions. My goal is to call one of the functions from within another function, as demonstrated in the code snippet below: .factory("AppStart", function($cordovaSQLite) { r ...

What is the process of implementing a particular FormControl from a FormArray in my HTML file?

My FormArray initialization code is as follows: this.contents.forEach(content=> { this.formArray.push( new FormControl(content.text, Validators.required)); }); Now, I am trying to associate a specific FormControl with my textarea by using i ...

Creating a two-column grid layout using Bootstrap 4 is a simple and efficient process. Let's see how

I've been struggling to get this to display side by side in a two-column grid. Even after following Bootstrap tutorials, I can't seem to make it work. Check out the code below: <div class="row"> <div class="col-md-8 ...

Encountering a blank page issue with Vue3 and Vite build deployment

I am currently working on a Vue 3 project with Vite. While the project runs smoothly in my local development environment, I encountered a problem when trying to build it using the command npm run build. Here is the content of my vite.config.js file: impor ...