I am new to learning React
.
I wanted to make it: when entering data into the input
, this data automatically appear in H1
in another component.
Screen.js
class Screen extends React.Component {
render() {
return (
<div className="screen">
<h1>Text from input</h1>
</div>
);
}
}
export default Screen;
Inputs.js
class Inputs extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Value: ' this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Enter" />
</form>
);
}
}
export default Inputs;
App.js
export default function App() {
return (
<div>
<h1>Hello StackBlitz!</h1>
<p>Start editing to see some magic happen :)</p>
<Inputs />
<Screen />
</div>
);
}
CodePudding user response:
write your app.js code as
export default function App() {
const [input,setInput] = useState('') const setInputValue = (value) => { setInput(value) } return (
{Hello StackBlitz!${input}
}
Start editing to see some magic happen :)
); }and inside your handleChange function write props.setInputValue(event.target.value)
and use input props in Screen.js file as props.input
CodePudding user response:
You have to lift the state up to the app.js
.
export default function App() {
const [val, setVal] = useState('');
return (
<div>
<h1>Hello StackBlitz!</h1>
<p>Start editing to see some magic happen :)</p>
<Inputs val={val} setVal={setVal} />
<Screen val={val}/>
</div>
);
}
Your inputs.js
export default const Inputs({val, setVal}) => {
const handleChange => (event) {
this.setState({value: event.target.value});
};
const handleSubmit => (event) {
alert('Value: ' this.state.value);
event.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={val} onChange={handleChange} />
<input type="submit" value="Enter" />
</form>
);
}
}
export default Inputs;
Your screen.js
export default const Screen({val}) => {
return (
<div className="screen">
<h1>{val}</h1>
</div>
);
}
```