Home > Back-end >  Is it possible to use arrow functions in react props?
Is it possible to use arrow functions in react props?

Time:04-18

I want to render components by mapping over a list that holds these components in JavaScript object literals. it iterates over the list and renders the components as desired, however, inside the Child component, I can see the props.myFunc is undefined, which was weird at first because changing myFunc to a regular JavaScript function (not arrow style) makes it work just fine, so what's happening?

  • Using react 18
  • This is not a bug in React 18, because I tried to run the same code on React 17, and it did same behavior.
class Child extends Component {
  render() {
    console.log(this.props.myFunc);
    return <></>;
  }
}
class Parent extends Component {
  list = [
    { btn: <Child myFunc={this.arrowFunc} /> },
    { btn: <Child myFunc={this.arrowFunc} /> },
    { btn: <Child myFunc={this.arrowFunc} /> },
  ];
  arrowFunc = () => {};
  render() {
    return this.list.map((item, i) => <div key={i}>{item.btn}</div>);
  }
}
export default Parent;

CodePudding user response:

Using the arrow function syntax is an Experimental Feature. As you suspected you need to Enable it in babel

Then main advantage of this syntax is that you don't need to bind your handler. You'll find more details in the React documentation about handling events.


EDIT:

Going beyond the scope of your question, storing the Child component in the list makes it a bit hard to understand what's going on. Generally speaking, you code could be refactored like so :


class Child extends Component {
  render() {
    console.log(this.props.myFunc);
    return <></>;
  }
}

class Parent extends Component {
  list = [
    { btn: {...someProps}},
    { btn: {...someProps} },
    { btn: {...someProps} },
  ];
  arrowFunc = () => {};
  render() {
    return this.list.map((item) => <Child {...item.btn} key={i} />);
  }
}
export default Parent;

This also remove the need for the extra div. However it might not do exactly what you want, it's hard to tell without a specific use case

  • Related