JavaScript React Components React Component Patterns Destructuring Props

Tom Stanley
Tom Stanley
14,640 Points

How would you destructure props in AddPlayerForm.js?

If I try to destructure this.props.addPlayer in the render method of AddPlayerForm, I get this error:

./src/components/AddPlayerForm.js
  Line 16:  'addPlayer' is not defined  no-undef

Is there a way around this, or can't you destructure this function from props in this case?

import React, { Component } from "react";

class AddPlayerForm extends Component {


  state = {
    value: ""
  };

  handleValueChange = (event) => {
    this.setState({ value: event.target.value })
  }

  handleSubmit = (e) => {
    e.preventDefault();
    addPlayer(this.state.value); // addPlayer this isn't defined yet
    this.setState({
      value: ""
    })
  }

  render() {

    const { addPlayer } = this.props;

    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type="text"
          placeholder="Enter a player's name"
          value={ this.state.value }
          onChange={this.handleValueChange}
        />

        <input
          type="submit"
          value="Add Player"
        />
      </form>
    );
  }
}

export default AddPlayerForm;
Mike Hatch
Mike Hatch
14,937 Points

Good question. I'm currently under the belief that you can't. There are no props to destructure here. There's only state.

1 Answer

Antoine Venco
Antoine Venco
4,782 Points

You need to declare the variable inside of your function in order for it to access the value, not sure if this is correct but it's working :

handleSubmit = (e) => {
    const { addPlayer } = this.props;
    e.preventDefault();
    addPlayer(this.state.value); // addPlayer this isn't defined yet
    this.setState({
      value: ""
    })
  }
Mike Hatch
Mike Hatch
14,937 Points

Hi Antoine,

It may work, but is that actually considered "Destructuring"? It doesn't seem to take away anything, it only adds. Also, addPlayer has already been declared in App.js. Take a look at the very bottom of the file:

<AddPlayerForm addPlayer={this.handleAddPlayer} />

As I understand it, addPlayer is a prop and is assigned the function handleAddPlayer. (Just a fellow student still learning, so I'm not positive I used correct terminology or not.)