Description: The given React code had issues with passing data between components. The App component was not passing the counter state to the Statetutorial component, and the Statetutorial component was not able to set the bet state in the App component. The code was fixed by passing the setBetValue function as a prop from the App component to the Statetutorial component, and using it to set the bet state in the App component when the increment function was called.
import React, { useState } from 'react';
import './style.css';
export default function App(props) {
const [counter, setCounter] = useState(0);
const increment = () => {
const newCounter = counter + 3;
setCounter(newCounter)
};
return (
<div>
<h1>Hello Fello</h1>
<div>{counter}</div>
<button onClick={increment}>increment</button>
<Statetutorial />
<br /> <br /> <br />
</div>
);
}
export function Statetutorial(props) {
const [bet, setBet] = useState('');
const onChange = (event) => {
const newValue = event.target.value;
setBet(newValue);
};
return (
<>
{props.counter}{bet}
<input placeholder="type" onChange={onChange} />
</>
);
}
my output is not as i need. i want to render App data in inside Statetutorial
2
Answers
It seems you dont pass any props to
try this:
If you want to have the state shared between components then you need to keep the state at the highest order component or use a library like react-redux to manage state between components. If you want to do it without redux you can do something like this. If you don’t want the ‘setBet’ and ‘setCounter’ in your app component then make a StateContainer component that has all the same logic and use the Statetutorial component.