S. Schenk
S. Schenk

Reputation: 2150

My onChange function is not being passed down to child

I'm building a higher component where field input is grouped together with some other components. I'm trying to pass down my onChange function to the child component so it can change the state with the new input. all the other props are passed fine and I can see the using chrome dev tools, but even though I can see the onChange function if I console.log the props on the child, it is not present on the form control component which ultimately creates the input text field.

Here is the code, you can notice in the form render the FormGroup which is not using the higher InputFieldGroup component:

higher_component.js

import React from 'react'
import * as FormGroup from 'react-bootstrap/lib/FormGroup'
import * as ControlLabel from 'react-bootstrap/lib/ControlLabel'
import * as FormControl from 'react-bootstrap/lib/FormControl'

export const InputFieldGroup = (props) =>
  <FormGroup
    controlId={props.controlId}
    validationState={props.validationState()}>
    <ControlLabel>{props.controlLabel}</ControlLabel>
    {console.log(props)} {/* I CAN SEE THE ONCHANGE FUNCTION HERE */}
    <FormControl
      type={props.type}
      name={props.name}
      value={props.value}
      placeholder={props.placeholder}
      onChange={props.handleChange}
    />
    <FormControl.Feedback />
  </FormGroup>

form.js

export default class RequestQuote extends Component {
  ...Some other class methods and stuff

  handleTextChange = (e) => {
    this.setState({ [e.target.name]: e.target.value })
  }

  render() {
    return(
      <form>

        <InputFieldGroup 
          controlId='email'
          validationState={this.emailValidationState}
          controlLabel='email'
          type='text'
          name='email'
          value={this.state.email}
          placeholder='Enter Business Email'
          onChange={this.handleTextChange}
        />
      {/* When I don't use the higher component the onchange works fine */}
        <FormGroup>
          <ControlLabel>Name</ControlLabel>
          <FormControl
            type='text'
            name='name'
            value={this.state.name}
            placeholder='Enter Name'
            onChange={this.handleTextChange}
          />
            <FormControl.Feedback />
        </FormGroup>
      </form>
    )
  }
}

Why isn't the onChange function being passed to the child input?

Upvotes: 1

Views: 1101

Answers (1)

Kerry Gougeon
Kerry Gougeon

Reputation: 1337

Because it is undefined! In fact you give

onChange={this.handleTextChange}

to the components as a props, if you want to call it do

props.onChange

and not

props.handleChange

otherwise, change the variable onChange={js} to handleChange={js}

Upvotes: 2

Related Questions