Yurgen
Yurgen

Reputation: 133

React handle state update

I'm using the react to build some input forms. While all children inputs have and their own states to store values I have no idea how to process the to a parent. Here's example:

class FormComponent extends Component {

    constructor(props) {
        super(props);

        this.state = {
            title: null,
            someAmount: null
        }
    }

    render() {
        let me = this;

        return (
            <div>
                <TextField
                    value={me.state.title}
                    onChange={(proxy, value) => {
                            me.setState({title: value})
                            me.hanleChnage();
                        }
                    }
                />
                <TextField
                    value={Number.parseFloat(me.state.someAmount)}
                    onChange={(proxy, value) => {
                            if (!isNaN(Number.parseFloat(value))) {
                                me.setState({someAmount: value})
                                me.hanleChnage();
                            }
                        }
                    }
                />
            </div>    
           )     
    }

    handleChange() {
        //Calling the parent
        //State here is outdated
        this.props.onUpdate && this.props.onUpdate(this.state);
    }
}

export default FormComponent;

Or where I can find some example of usage of compex forms with much inputs in react. Thanks!

Upvotes: 0

Views: 1018

Answers (2)

ScoobyDrew18
ScoobyDrew18

Reputation: 631

Sounds like you need to consider moving some of your state into the parent components. The React docs have a good article about this.

To summarize, you can pass your hanleChnage(); function as a prop to your child components if you declare the function in your parent.

function handleChange() { //do something... }
...
<ChildComponent parentOnChange={this.handleChange.bind(this) />

As your components grow in complexity, you might consider using Redux for state management, thus serving as a single source for all state in your application.

Upvotes: 3

user463535
user463535

Reputation:

Set a child property, (e.g. callParentProperty) to reference a function in the parent component (e.g. parentFunction).

class ParentComponent extends Component{
   parentFunction(parameter) {
      console.log("This is the form value");
      console.log(parameter);
   }
   render() {
      return <FormComponent callParentFunctionProperty={this.parentFunction.bind(this)} />
   }
}
class FormComponent extends Component {
    ...
    handleChange() {
      ...
      let formValue = this.state.someAmount;
      this.props.callParentFunctionProperty(formValue);
    }
}

Upvotes: 1

Related Questions