This is probably a very newbie question, but I can't figure out how to know what parameters are passed to a function. Let me show you what I mean:
I have the following code in my constructor:
this.handleFormInput = this.handleFormInput.bind(this);
And then:
handleFormInput(event) {
console.log('event' + event.target.name);
this.setState({
[event.target.name]: event.target.value
})
}
And finally the form:
<Form>
<Form.Group>
<Form.Field style={{width: '90%'}}>
<input placeholder='Section title'
id={section.id}
name='title'
value={section.title}
onChange={this.handleInput}
/>
</Form.Field>
</Form.Group>
</Form>
So far so good: the event parameter is passed automatically and I can reach it by adding it as a parameter in my function.
Now I have a Dropdown component. In the constructor I have:
this.handleDropDownInput = this.handleDropDownInput.bind(this);
The function:
handleDropDownInput(event, data) {
console.log('value ' + data.value);
this.setState({
[data.name]: data.value
})
}
Then the semantic-ui
Dropdown:
<Dropdown
fluid
placeholder='Language'
search
selection
options={languages}
defaultValue='gb'
name='language'
onChange={this.handleDropDownInput}
/>
Why I have to use the 'data' parameter to get the value on the Dropdown component? Why I can't use just the event? How can I know what parameters are passed automatically when onChange is triggered?
Is it appropriate to have a different function for different input components (dropdown, form fields etc)? Can and should I make one function to manage all user input?
For example, I came up with this function to handle both dropdown and form fields onChange events:
handleInput(event, data) {
if (data !== undefined) {
console.log('value ' + data.value);
this.setState({
[data.name]: data.value
})
} else {
console.log('event ' + event.target.name);
this.setState({
[event.target.name]: event.target.value
})
}
Is it good or bad practice? Thanks.
In javascript there are a few ways you can get all the arguments, depending on your environment.
In pre-es6 javascript (pre "strict mode," which is what es6 modules default to) there was a dynamic variable called "arguments." You can see a reference to it here: mdn
In newer es6 style environments, you can use what is called "rest parameter syntax" to get something similar, which will be an array of the arguments. mdn
In general, that information should be in the docs for the library or react component you are using.
function someFn(...args) {
console.log(args)
}
someFn("hey", "there");