I'm making an input component and i want to use it whereever i want.
input component code:
import React from "react";
import PropTypes from "prop-types";
class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
[props.name] : props.value
};
this.handleUserInput = this.handleUserInput.bind(this)
}
handleUserInput(e){
console.log(e.target.name);
this.setState( prevState => ({
[e.target.name] : e.target.value
}));
}
render() {
const {
type,
value,
placeholder,
className,
name,
id,
form_control,
disabled,
readOnly,
minLength,
maxLength,
ref,
autoFocus,
message
} = this.props;
let CLASS =
(form_control ? "form-control" : "") + " " + (className || "");
if ( message ){
CLASS += (className ? ' ' : '') + 'is-invalid ';
}
return (
<input
type={type}
name={name}
value={this.state[name]}
placeholder={placeholder}
className={CLASS}
id={id}
disabled={disabled}
readOnly={readOnly}
minLength={minLength}
maxLength={maxLength}
ref={ref}
autoFocus={autoFocus}
onChange={this.handleUserInput}
/>
);
}
}
Input.defaultProps = {
type: "text",
form_control: true,
value : ""
};
Input.propTypes = {
type: PropTypes.string,
value: PropTypes.string,
placeholder: PropTypes.string,
className: PropTypes.string,
name: PropTypes.string.isRequired,
id: PropTypes.string,
form_control: PropTypes.bool,
disabled: PropTypes.bool,
readOnly: PropTypes.bool,
minLength: PropTypes.number,
maxLength: PropTypes.number,
ref: PropTypes.string,
autoFocus: PropTypes.bool
};
export default Input;
confirmable component code :
import React from "react";
import PropTypes from "prop-types";
import Input from "./input";
import FeedBack from "../static/feedback";
class ConfirmAble extends React.Component {
constructor(props) {
super(props);
}
render() {
const { message } = this.props;
return (
<div>
<Input {...this.props} />
<FeedBack text={message} />
</div>
);
}
}
ConfirmAble.propTypes = {
message: PropTypes.string.isRequired
};
export default ConfirmAble;
I'm using this confirmable component many times in same component like below :
<ConfirmAble
type="email"
name="email"
value={this.state.email}
message={this.state.formErrors.email}
/>
<ConfirmAble
type="password"
name="password"
value={this.state.password}
message={this.state.formErrors.password}
/>
but input valuee can not change. if i added handleUserInput function to component i got this error
TypeError: Cannot read property 'name' of null at t. (input.jsx:19)
line 19 is
[ e.target.name ] : e.target.value ( in the handleUserInput function )
If I remove one of component, it works.
Why does not work? Where is the problem ?