Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: how to notify parent for changes

Tags:

reactjs

I'm trying to wrap bootstrap into components with integrated form validation.

short: Let's say I have

<Form>
  <FieldGroup>
     <Field rules={'required'}/>
  </FieldGroup>
</Form>

Once Field pases validation, how can I notify FieldGroup (parent node) to add a class?

I created a simplified codepen version here

I would like depending on validation status, then change the state of FieldGroup So I can properly change the class name. (add has-warning has-danger etc) and ultimately add class to the Form component.

like image 277
Yichaoz Avatar asked Nov 16 '16 23:11

Yichaoz


1 Answers

You need to pass a callback to the child component. I just forked your codepen and added some snippet as below.

http://codepen.io/andretw/pen/xRENee

Here is the main concept, Make a callback function in "parent" component and pass it to the "child" component

i.e. The child component needs an extra prop to get the callback:

<Form>
  <FieldGroup>
     <Field rules={'required'} cb={yourCallbackFunc}/>
  </FieldGroup>
</Form>

In <FieldGroup /> (parent):

class FieldGroup extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      color: 'blue'
    }
  }

  cb (msg) {
    console.log('doing things here', msg)
  }

  render() { 
    const childrenWithProps = React.Children.map(this.props.children,
     child => React.cloneElement(child, {
       cb: this.cb
     })
    )
    return (
      <div class='fields-group'>
        <label> field </label>
        { childrenWithProps }
      </div>
    );
  }
};

In <Field /> (child):

class Field extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      empty: true
    }
    this.validate = this.validate.bind(this);
  }

  validate(e){
    let val = e.target.value;
    console.log(!val);
    this.setState({empty: !val});
    //here to notify parent to add a color style!

    // do call back here or you may no need to return.
    this.props.cb(val)

    return !val;
  }

  render() {
    return (
      <div>
        <input type='text' onBlur ={(event) => this.validate(event)}/>
        {this.state.empty && 'empty'}
      </div>
    );
  }
};

And you can do the things you want in the callback function. (You can also pass a callback from <Form /> to the grandson and get it work, but you need to rethink the design of it is good or not.)

like image 123
Andre Lee Avatar answered Nov 15 '22 21:11

Andre Lee