Alex Alex - 2 months ago 21
Javascript Question

React passing onChange event down to child component

I have the following:

import React from 'react';
import {render} from 'react-dom';

import Form from './form.jsx';

import axios from 'axios';

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
location: ''
};
}
getSearchedValue(e) {
this.setState({ location: e.target.value });
}
searchNearPlaces (e) {
e.preventDefault();

console.log(this.getSearchedValue());

const clientID = 'xxxxxxxxxxx',
clientSecret = 'xxxxxxxxxxxxx',
version = 'v=20140806';
let location = this.state.location,
url = 'https://api.foursquare.com/v2/venues/explore?client_id=' + clientID + '&client_secret=' + clientSecret + '&near=' + location + '&' + version;

axios.get(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
render () {
return (
<section className="main">
<Form action={this.searchNearPlaces.bind(this)} value={this.getSearchedValue.bind(this)} />
</section>
);
}
}

render(<App/>, document.getElementById('app'));


and a form component:

import React from 'react';

class Form extends React.Component {
render () {
return (
<form className="form-group">
<input type="text" onChange={this.props.value} />
<input onClick={this.props.action} type="submit" />
</form>
);
}
}

export default Form;


the moment I click on submit after having typed 'london' for example I get the following error:

Uncaught TypeError: Cannot read property 'target' of undefined


referring to:

getSearchedValue(e) {
this.setState({ location: e.target.value });
}

Answer

Likely because of this line in your code:

console.log(this.getSearchedValue());

Since you are not passing anything to it, e is undefined.