Home > front end >  How to send functional data to another page in React
How to send functional data to another page in React

Time:01-02

Playing.js File

import { useState } from "react";
function Playing(){
  const [sidebar, setSidebar] = useState(false);

  const sidebarFunc = () => {
    sidebar ? setSidebar(false) : setSidebar(false);
  }

  return(
    <i onClick={sidebarFunc}>Click</i>
  );
}

export default Playing;

Sidebar.js File

function SideBar() {
  return (
    <div className="">Side Bar</div>
  );
}

export default SideBar;

App.js File

import Sidebar from "./Sidebar.js";
import Playing from "./Playing.js";
function App(){
  return(
    <>
      <Sidebar />
      <Playing />
    </>
  );
}

I'm new to react, so try avoiding mistakes by my side. Here i'm trying a way in which the after clicking the Click text, the usestate variable sidebar gets triggered. But the sidebar couldn't be exported so as to get an outcome for Sidebar functional div as <div className="sidebar?"Show":"Hide">Side Bar</div>.

Is there a solution for the same or any other ways it can be done. Thank you in advance

CodePudding user response:

You can create a state in parent component and then use this state in child component by passing through props and a callback function

App.js File

import Sidebar from "./Sidebar.js";
import Playing from "./Playing.js";
function App(){

 const [sidebar, setSidebar] = useState(false);

  return(
    <>
      <Sidebar sidebar={sidebar}/>
      <Playing  sidebar={sidebar} setSidebar={setSidebar}/>
    </>
  );
}

Playing.js

import from "react";
function Playing({sidebar,setSidebar}){


  const sidebarFunc = () => {
    sidebar ? setSidebar(false) : setSidebar(false);
  }

  return(
    <i onClick={sidebarFunc}>Click</i>
  );
}

export default Playing;

SideBar.js

   function SideBar({sidebar}) {
      return (
        <div className=`${sidebar?"Show":"Hide"}`>Side Bar</div>
      );
    }
    
export default SideBar;

CodePudding user response:

Place the useState() declaration in App.js.

App.js

function App(){
    const [sidebar, setSidebar] = useState(false);

    return(
        <>
            <Sidebar sidebar={sidebar}/>
            <Playing sidebar={sidebar} setSidebar={(bool) => setSidebar(bool)}/>
        </>
    );
}

SideBar.js

function SideBar(props) {
  return (
    <div className={props.sidebar ? "Show" : "Hide"}>Side Bar</div>
  );
}

export default SideBar;

Playing.js

function Playing(props){
    const sidebarFunc = () => {
        props.sidebar ? props.setSidebar(false) : props.setSidebar(false);
    }

    return(
        <i onClick={sidebarFunc()}>Click</i>
    );
}

export default Playing;
  • Related