Search code examples
reactjsreactstrapinput-maskreact-hook-form

It is possible to use reactstrap with react-hook-form and react-input-mask?


I've been trying for a while but without any success. I've managed to implement reactstrap + react-hook-form and reactstrap + react-input-mask but not the three of then together. Here's the code running: https://stackblitz.com/edit/reactstrap-v5beta-input-mask-yu6zii?file=Example.js

import React from 'react';
import { Input } from 'reactstrap';
import useForm from 'react-hook-form'
import InputMask from 'react-input-mask';

const Example = () => {
  const { register, handleSubmit, errors } = useForm()
  const onSubmit = data => console.log(data)

  console.log(errors)

  return (
    <div>
      <form onSubmit={handleSubmit(onSubmit)}>
        <label>react-hook-form</label>
        <Input 
          type='text' 
          name='input-1'
          invalid={errors['input-1']}
          innerRef={register({ required: true })}
        />
        <br />
        <label>react-input-mask</label>
        <Input
          type="tel"
          mask="+4\9 99 999 99"
          maskChar=" "
          tag={InputMask}
        />
        <br />
        <input type="submit" />
      </form>
    </div>
  )
}

export default Example;

Solution

  • Did you add Bootstrap to your project? Reactstrap does not come with it right out of the box.

    "Install reactstrap and Bootstrap from NPM. Reactstrap does not include Bootstrap CSS so this needs to be installed as well:

    npm install --save bootstrap
    npm install --save reactstrap react react-dom
    

    Import Bootstrap CSS in the src/index.js file:

    import 'bootstrap/dist/css/bootstrap.min.css';
    

    Import required reactstrap components within src/App.js file or your custom component files:

    import { Button } from 'reactstrap';
    

    Now you are ready to use the imported reactstrap components within your component hierarchy defined in the render method. Here is an example App.js redone using reactstrap."