I have a component that generates input in Form. I'm trying to pass a function to OnChange event, but always getting error
import { FormGroup, FloatingLabel, FormControl } from "react-bootstrap";
const FormInput = (props) =>{
return(
<FormGroup controlId={props.controlId} className="mb-3">
<FloatingLabel label={props.label}>
<FormControl type={props.type} name={props.controlId} placeholder={props.label} onChange={props.onChange} />
</FloatingLabel>
</FormGroup>
)
}
export default FormInput;
And in my App I'm passing props to Component. Can't figure out how to pass function to get value on input
import React, { Component } from "react";
import {
Container,
Row,
Form,
Button,
} from "react-bootstrap";
import FormInput from "./FormInput";
import { FormGroup, FloatingLabel, FormControl } from "react-bootstrap";
class AddRecipe extends Component {
constructor() {
super();
this.state = {
recipeImage: "",
recipeName: "",
recipeIngredients: "",
};
this.handleChange = this.handleChange.bind(this);
}
handleChange = (e) =>{
this.setState({
[e.target.name]: e.target.value,
});
}
render() {
return (
<Container>
<Row>
<Form inline="true" className="mt-5">
<FormInput
controlId="recipeImage"
label="Image URL"
type="url"
handleChange={this.handleChange}
/>
<FormInput
controlId="recipeName"
label="Recipe Name"
type="text"
handleChange={this.handleChange}
/>
<FormInput
controlId="recipeIngredients"
label="Ingredients"
type="textarea"
handleChange={this.handleChange}
/>
<Button>Add</Button>
</Form>
</Row>
</Container>
);
}
}
export default AddRecipe;
How to pass handleChange function as props, so I can write value to my state?
The problem is that in your component, you define the prop as onChange, but in your app, you pass the prop handleChange. To fix the error, just change the name of the prop you pass in your app:
<FormInput
controlId="recipeImage"
label="Image URL"
type="url"
onChange={this.handleChange}
/>
{/* this `onChange` prop should fix it */}
My mistake, I was using a different name for props.
Ater changing
<FormInput
controlId="recipeIngredients"
label="Ingredients"
type="textarea"
handleChange={this.handleChange}
/>
to
<FormInput
controlId="recipeIngredients"
label="Ingredients"
type="textarea"
onChange={this.handleChange}
/>
It fixed issue. Thank you