9

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.

Yichz
  • 9,250
  • 10
  • 54
  • 92

1 Answers1

13

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.)

Andre Lee
  • 1,180
  • 1
  • 11
  • 13
  • is it using cloneElement slows the app? now every render would have to map and merge the cb, – Yichz Nov 17 '16 at 20:35
  • That part is for *adding a prop to each child in this.props.children*, you can also check the comments below [this answer](http://stackoverflow.com/questions/35835670/react-router-and-this-props-children-how-to-pass-state-to-this-props-children). I didn't do the benchmark for this but it should be okay if you have only a few of `this.props.children` in the component. – Andre Lee Nov 18 '16 at 02:02