I am trying to print addition of two number using React JS
function App() {
return (
<div>
<InputNumbers />
<PrintAddition />
</div>
);
}
App Contains two components PrintAddition & InputNumbers, Where InputNumbers components take values from inputs and that data has to be sent to it sibiling component PrintAddition, How ?
function PrintAddition() {
return (
<div>
<p>
The addition of numbers is <span>{Here result has to be printed }</span>
</p>
</div>
);
}
function InputNumbers() {
const [num1, setnum1] = useState(0);
const [num2, setnum2] = useState(0);
return (
<div>
<input
className="num1"
type={"text"}
onChange={(e) => setnum1(e.target.value)}
></input>
<input
className="num2"
type={"text"}
onChange={(e) => setnum2(e.target.value)}
></input>
</div>
);
}
2
Answers
You need to move state to the App component and use props to pass them into specific components.
There are many ways of doing this. One of the easiest is to let
App
hold the state and send it toPrintAddition
.You’ll need to send the
setter
funciton toInputNumbers
so they can call it in theonChange
.Another option would be to use something like React Redux to save that data in a Store.
Demo based on OP"s code: