This question already has answers here:
How to pass data from child component to its parent in ReactJS?
(18 answers)
Closed 5 years ago.
I can't figure out why I can't get data at my parent component.
I have parent component - AddButton , and child component - AddTasktBox. I want to pass title from child to parent.
Probably bad is in AddButton component - because browser is give me error like this:
"TypeError: _this2.props.sendData is not a function"
Just look at submit - input "onClick={this.handleClick}"(bottom) - there's start my code to passing
import React from 'react';
import ReactDOM from 'react-dom';
class AddButton extends React.Component{
constructor(props){
super(props);
this.state = {
isHidden: false,
title: '',
};
}
sendData = (data) => {
console.log(data);
this.setState({
title: data
})
};
toggleHidden = () => {
this.setState({
isHidden: !this.state.isHidden
})
}
render(){
return(
<div>
<div
onClick={this.toggleHidden.bind(this)}
className="addtask__btn">
+
</div>
{this.state.isHidden && <AddTaskBox handleClose={this.toggleHidden.bind(this)} handleClick={this.sendData.bind(this)}/>}
</div>
);
}
}
class AddTaskBox extends React.Component{
constructor(props){
super(props);
this.state = {
title: '',
description: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
handleClick = () => {
this.props.sendData(this.state.title);
}
render(){
return(
<div className="addtask__box" >
<div className="addtask__close" onClick={this.props.handleClose}>X</div>
<form >
<input
type="text"
name="title"
placeholder="Nazwa Czynności"
value={this.state.title}
onChange={this.handleChange}/>
<textarea
name="description"
value={this.state.description}
onChange={this.handleChange}
placeholder="Opis czynności">
</textarea>
<input
className="btn"
type="submit"
value="submit"
onClick={this.handleClick}/>
</form>
</div>
);
}
}
export {AddButton, AddTaskBox};
You aren't passing sendData() as a prop to AddTaskBox
<AddTaskBox sendData={this.sendData} />
Related
import React, { Component } from "react";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { value: "" };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
console.log(this.state.value);
this.setState({ value: event.target.value });
}
render() {
return (
<form>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
console log screenshot
I'm getting first input value empty. I have different app. I'm basically try to doing tip calculator app. I don't need submit button. The user will enter a value, but it does not calculate correctly because the first value is empty. At the same time, it does not show the last value entered, only when clicked, all the entered values are correct. By the way, i got this form from React own site, but it's the same error that i encountered. Thank you!
Your console.log logs the value before you change it. Thus it will always be the previous value.
You also have to keep in mind that the Component.setState method might not execute immediately.
Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
Therefore you should use a callback. E.g.
handleChange(event) {
this.setState({ value: event.target.value }, () => {
console.log(this.state.value);
});
}
Here is an executable example. Click Run code snippet.
class App extends React.Component {
constructor(props) {
super(props);
this.state = { value: "" };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value }, () => {
console.log(this.state.value);
});
}
render() {
return (
<form>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Set initial value to 0 so that it will not be empty.
this.state = { value: 0 };
Also move your console.log as callback function to setState so that you can see the updated value.
import React, { Component } from "react";
export default class App2 extends React.Component {
constructor(props) {
super(props);
this.state = { value: 0 };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value }, () => {
console.log(this.state.value);
});
}
render() {
return (
<form>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
import React from 'react';
import Child from './Child';
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {
firstName: ""
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount(){
let fn = JSON.parse(localStorage.getItem("fir"));
if((localStorage.getItem("fir")!==undefined) && (localStorage.getItem("fir")!==null)){
this.setState({
firstName: fn
})
}
}
handleChange(e){
this.setState({
[e.target.name] :[e.target.value]
})
}
handleSubmit(){
localStorage.setItem("fir", JSON.stringify(this.state.firstName));
alert('submitted');
console.log(this.state.firstName)
}
render(){
return(
<div>
<p> Parent</p>
<Child
firstName={this.state.firstName}
handleChange={this.handleChange}
handleSubmit={this.handleSubmit}
/>
{this.state.firstName}
</div>
)
}
}
export default Parent;
2.
import React from "react";
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: props.firstName
};
}
render() {
return (
<div>
<p> Child</p>
<input
type="text"
name="firstName"
value={this.state.firstName}
onChange={this.props.handleChange}
/>
<button onClick={this.props.handleSubmit}> submit</button>
</div>
);
}
}
export default Child;
Here i want to update an input field in Child component, But i'm stucked. can anyone help to update that.
Change the below line in child
value={this.state.firstName}
to
value={this.props.firstName}
because firstname is being passed as a prop to child component
You need to pass the value you need to update has props then use that props in the value of your input in child component. I can see you already passing the firstName has a prop, you just to change state to props
<input
type="text"
name="firstName"
value={this.props.firstName}
onChange={this.props.handleChange}
/>
When I insert any text in input field, screen disappears, I am new to UI, learning ReactJs, help me out please.
import React from 'react';
class InputChange extends React.Component{
constructor(props){
super(props)
this.state={
input:''
}
}
updateState = (text) => {
this.setState({input: text});
}
render(){
return(
<div>
<div>Input:{this.state.input}</div>
<div>
<input type="text" value={this.state.input} onChange={this.updateState} />
</div>
</div>`
);
}
}
export default InputChange;
It's event.target.value...:
class InputChange extends React.Component {
state = { input: '' };
updateState = event => {
this.setState({ input: event.target.value });
};
render() {
return (
<div>
<div>Input:{this.state.input}</div>
<div>
<input
type="text"
value={this.state.input}
onChange={this.updateState}
/>
</div>
</div>
);
}
}
export default InputChange;
More info in the docs: https://reactjs.org/docs/forms.html
I want to make a component with an API like any standard input element, meaning I want to use it like this: <CustomInput value={this.state.custom_input_state} onChange={this.handleChange} />
Here is what I have so far, but I have no idea how to
Make the custom components value changeable from the parent component
after it has been constructed
Make the parent's onChange handler function recieve a change event when the
custom component's value changes
Here is my test setup:
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
foo: 0
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.increment = this.increment.bind(this);
}
handleChange(event) {
this.setState({[event.target.name]: event.target.value});
}
handleSubmit(event) {
alert(this.state.foo);
event.preventDefault();
}
increment() {
this.setState({foo: this.state.foo + 1});
}
render() {
return(
<form onSubmit={this.handleSubmit}>
<div onClick={this.increment}>Increment from parent</div>
<CustomInput name="foo" value={this.state.foo} onChange={this.handleChange}/>
<input type="submit" value="Submit" />
</form>
)
}
}
class CustomInput extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.value,
};
this.increment = this.increment.bind(this);
}
increment() {
this.setState({value: this.state.value + 1});
}
render() {
return(
<React.Fragment>
<div onClick={this.increment}>Increment self</div>
<input name={this.props.name} value={this.state.value}/>
</React.Fragment>
);
}
}
You have to pass all the CustomInput props to the input element. In CustomInput component actually it not recieving the onChange event.
Pass the prop onChange event to input element
Form Component
class Form extends Component {
constructor() {
super();
this.state = {
foo: 'React'
};
}
handleChange = (event) => {
this.setState({
[event.target.name]:event.target.value
})
}
render() {
return (
<div>
<form>
<Custominput name="foo" onChange={this.handleChange} value={this.state.foo} />
</form>
{this.state.foo}
</div>
);
}
}
CustomInput Component
export default class CustomInput extends React.Component{
render(){
return(
<input {...this.props} />
)
}
}
demo link
This question already has answers here:
How to pass data from child component to its parent in ReactJS?
(18 answers)
Pass props to parent component in React.js
(7 answers)
Closed 5 years ago.
In react js I have 2 components.
In Component1.jsx :
import Info from Component2.jsx;
...
...
var dataInfo = "some info.. ";
<Info dataInfo={dataInfo} />
...
...
Here in the above code, we'r transfering the data in the form props from component1.jsx to component2.jsx
In the same fashion can we transfer back to data to component2.jsx to component1.jsx ?
Please help me out here. I'm trying to find the answer in google but couldn't get properly.
Yes you can transfer back to parent component,
i will give you an example to show clearly how you can do that
suppose you have a parent it's called component1 and it have a form imported as a child in it called component2
as the follow:
import React, { Component } from 'react';
export default class Component2 extends Component{
constructor() {
super();
this.state = {
UserName: '',
email: ''
};
this.onSubmit = this.onSubmit.bind(this)
}
onSubmit(e){
e.preventDefault();
var field = {
UserName: this.state.UserName,
email : this.state.email,
password: this.state.password,
}
**this.props.onUpdate(field);**
}
onChange(e){
this.setState({
[e.target.name]: e.target.value
});
}
render() {
var UserNameError = **this.props.UserNameError**;
var emailError = **this.props.emailError**;
return(
<div className="col-md-6 col-sm-6">
<div className="title">Create Account</div>
<Form onSubmit={this.onSubmit}>
<div className="form-group">
<label>user Name</label>
<input onChange={this.onChange.bind(this)} value={this.state.UserName} name='UserName'/>
<span className="error is-visible">{UserNameError}</span>
</div>
<div className="form-group">
<label>Email</label>
<input onChange={this.onChange.bind(this)} value={this.state.email} name='email' />
<span className="error is-visible">{emailError}</span>
</div>
<Button className='btn submit'>Register</Button>
</Form>
</div>
)
}}
import React, { Component } from 'react';
import Component2 from './Component2'
export default class Component1 extends Component{
constructor() {
super();
this.state = {
UserName: '',
email: '',
UserNameError:' UserNameError ',
emailError:' emailError '
};
}
onUpdate(val) {
this.setState({
email: val.email,
UserName: val.UserName,
});
console.log(' onSubmit ** email' + val.email + " UserName " + val.UserName )
};
render() {
return(
<div className="col-md-6 col-sm-6">
<Component2 **UserNameError={this.state.UserNameError}** **emailError={this.state.emailError}** **onUpdate={this.onUpdate.bind(this)}** />
</div>
)
}
}
I put the stars around sentence to notice how I transfer data errors from parent Component1 to component2
and how I send Form data by onUpdate function from child Component2 to Component1