Home > Enterprise >  I want to control value of input in parent component (Child is PureComponent)
I want to control value of input in parent component (Child is PureComponent)

Time:02-01

Before question, sorry for massy code because I'm newbie at code.

I made Input component by PureComponent. But I have no idea how to control(like change state) & submit its value in Parent component.

this is Input PureComponent I made:

index.jsx

class Input extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            value: props.value,
            name: props.value,
        };
        this.setRef = this.setRef.bind(this);
        this.handleChange = this.handleChange.bind(this);
    }

    setRef(ref) {
        this.ref = ref;
    }

    handleChange(e) {
        const { name, onChange, type } = this.props;
        onChange(name, e.target.value);
        this.setState({ isInputError: checkError, value: e.target.value });
    }

render() {
    const { label, name, type} = this.props;
    return (
        <div className="inputBox">
            <input
                id={name}
                value={this.state.value}
                type={type}
                ref={this.setRef}
                onChange={this.handleChange}
                className="BlueInput"
            />
            <label>{label}</label>
        </div>
    );
}
}

Input.propTypes = {
    label: PropTypes.string,
    name: PropTypes.string.isRequired,
    value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    type: PropTypes.oneOf(["text", "password", "number", "price", "tel"]),
    onChange: PropTypes.func,
}

Input.defaultProps = {
    value: "",
    type: "text",
    onChange: () => { },
}

export default Input;

And this is Parent component where I want to control value

Join.js

function Join() {
  const [idMessage, setIdMessage] = useState("");
  const [isId, setIsId] = useState(false);

  const onChangeId = (name, value) => {
    const currentId = value;
    const idRegExp = /^[a-zA-z0-9]{4,12}$/;

    if (!idRegExp.test(currentId)) {
      setIdMessage("Wrong format");
      setIsId(false);
    } else {
      setIdMessage("You can use this");
      setIsId(true);
    }
  }

  const handleSubmit =  (e) => {
    e.preventDefault();
    let formData = new FormData();
    console.log(formData);
    alert("Join completed.");
  }

  return (
    <div className="join-wrap">
        <form encType="multipart/form-data" onSubmit={handleSubmit}>
          <Input name="id" label="ID" onChange={onChangeId} />
          <p className={isId ? 'possible' : 'impossible'}>{idMessage}</p>
          <button type="submit">Join</button>
        </form>
    </div>
  )
}

export default Join;

How can I control or submit value?

CodePudding user response:

For anyone landing here with a similar question, I would advise you to use functional components. For the custom input component, you do not really need to define any state in the custom component. You can pass the state (value of input) as well as the change handler as prop to the child component. In case you need refs, use forwardRef.

Intentionally, I am not spoon-feeding here. I am just giving food for thought and some keyword to do a quick research and enhance your skills.

CodePudding user response:

index.js

handleChange(e, fieldName) {
  this.props.setState({...this.props.state, [fieldName]:e.target.value})
 }
-----------------------

<input
  id={this.props.name}
  value={this.props.state[name]}
  type={type} // you can also add type in state
  onChange={(e)=>this.handleChange(e, name)}
  className="BlueInput"
 />

join.js

const [state,setState] = useState({fName:'',lNAme:''})
{Object.keys(state).map((value)=>{
    return <Input name={value} label="ID" state={state} setState = {setState}/>
})}

  • Related