I have some code on react that uses two independent components. On clicking a button in the first component, I hide the current component and display the other component. But also, I want to pass some values from the first component (from INPUTS) to the second component. Can you please tell me how can I do that? Here is the code:
App.js
import React from 'react';
import { useState } from 'react';
import { FirstSection} from './components/FirstSection';
import { SecondSection} from './components/SecondSection';
function App() {
const [checkSection, setSection] = useState(false);
const showSecondSection= () => setSection(true);
return (
<div className="App">
{checkSection ? <SecondSection /> : <FirstSection onClick={showSecondSection} />}
</div>
);
}
export default App;
FirstSection.jsx
import { useState } from 'react';
export function FirstSection({onClick}) {
const [Value, setValue] = useState();
return(
<>
<input type="text" value="{input1}" />
<input type="text" value="{input2}" />
<button onClick={onClick}>Continue</button>
</>
)
}
SecondSection.jsx
export function SecondSection() {
return(
<>
<p>{input1}, {input2}</p> <== here I want to pass data from the first component
</>
)
}
2
Answers
Used context
You can get
{ inputValues, setInputValues }
from context at below the App level in render tree. I am setting the inputValues in first section and retrieving it in second section.If you wanna play around with code.
You can also pass setter function (setInputValues) to FirstSection and state (inputValues) to SecondSection as prop, it will work the same.
you can have a state in the App component and then pass the value to the
SecondSection
component and the setState function to theFirstSection
component.