Could somebody please explain how passing functions to child components in ReacJS works?

For some context, Im creating a color picker component. My app component has a function that deals with the click of one of the sample colors in the color picker component. Within the color picker component is an array of available colors which is mapped to buttons.

I keep receiving the error “TypeError: Cannot read property ‘props’ of undefined” which is created by my button code below.

export default class ColorPicker extends React.Component {
	constructor(props) {
		super(props);


		const colors = [
			'black',
			'hot-pink'
		]

		const buttons = colors.map(function(value, key) {
			return (
				<button key={key} className={ 'btn btn-light btn-color svg-' + value } onClick={ this.props.colorClick('svg-' + value) }></button>
			);
		});

		this.state = {
			'colors' : colors,
			'buttons' : buttons
		};
	}

	render() {
		return (
			<div>
				{ this.state.buttons }
			</div>
		);
	}
}

The parent component just runs

<ColorPicker colorChange={ this.colorChange.bind(this) }/>

Do I need to bind the function somewhere and if so where? Remember the function is being passed down as a property of the component.

I see your are referring to this.props. What does the entire function look like which contains the code above? Also, what does the component code look like which passes a prop named colorClock to this function?

It is always best if you can provide a link to your entire project code or at least the relevant components/functions. Otherwise, we are just guessing what the problem may be. Many people use Codepen.io to post their code or codesandbox.io.

Edited, sorry about that

I bet you have a reference error showing in your browser console, because you make a reference to this.props.colorClick in the onClick handler, but you are passing a prop named colorChange to the ColorPicker component.

Also, the error you say you are receiving above, what line of code does it reference in the error message? You really should post all your code. You will get better responses to help you.

I fixed the error, it turns out it was because of the way I used map.

I did

array.map(function(value, key) {

});

The way I should have done it was.

array.map((value, key) => {

});

I figured this out by console logging this.props in the map and outside it of course it only worked outside because () => {} changes the way this is interpreted.