I want to get value from child components to parent components.
Here is my code.
//this is child component
import { React } from "react";
const Tab = () => {
const changeTab = (index) => {
console.log(index);
};
return (
<>
<div className="flex gap-10">
<button
onClick={() => changeTab(1)}
className="bg-gray-700 p-2 text-white"
>
btn1
</button>
</div>
</>
);
};
export default Tab;
//this is parent component
import React from "react";
import Nav1 from "./Components/Navbar/Nav1";
import Tab from "./Tab";
const App = () => {
return (
<>
<Tab />
<div>
<Nav1 />
</div>
</>
);
};
export default App;
I want to log the value of the index in a parent component that was coming from a child.
CodePudding user response:
define changeTab
in parent component and pass it through props to Tab
.
parent:
import React from "react";
import Nav1 from "./Components/Navbar/Nav1";
import Tab from "./Tab";
const App = () => {
const changeTab = (index) => {
console.log(index);
};
return (
<>
<Tab changeTab={changeTab}/>
<div>
<Nav1 />
</div>
</>
);
};
export default App;
and child component:
import { React } from "react";
const Tab = ({changeTab}) => {
const onChangeTab = (index) => {
changeTab(index);
// other stuff
};
return (
<>
<div className="flex gap-10">
<button
onClick={() => onChangeTab(1)}
className="bg-gray-700 p-2 text-white"
>
btn1
</button>
</div>
</>
);
};
export default Tab;
CodePudding user response:
You can use context API:
https://reactjs.org/docs/context.html
Or you can transfer changeTab function to parent component and pas it as prop
CodePudding user response:
Your problem is common(with most people). And the solution is to lift the state up(React docs). Which basically means, you'll have to maintain the state in the parent component and pass the value and method to the child component.
// App.jsx
import React from "react";
import Nav1 from "./Components/Navbar/Nav1";
import Tab from "./Tab";
const App = () => {
const changeTab = (index) => {
console.log(index);
};
return (
<>
<Tab handleTabChange={changeTab}/>
<div>
<Nav1 />
</div>
</>
);
};
export default App;
import { React } from "react";
const Tab = (props) => {
const changeTab = (index) => {
props.handleTabChange(index);
};
return (
<>
<div className="flex gap-10">
<button
onClick={() => changeTab(1)}
className="bg-gray-700 p-2 text-white"
>
btn1
</button>
</div>
</>
);
};
export default Tab;