A customizable phone input component with country codes for both standard JavaScript and React-based applications.
- Country selection with flags and codes.
- Phone number formatting based on the selected country.
- Support for both standard JavaScript and React.
- Dropdown search for countries.
- ESModule support.
- Turbo compatibility for seamless integration with Turbo-enabled applications.
To install the library, run:
npm install inflag
import InFlag from 'inflag';
import 'inflag/dist/style.css';
const phoneInput = new InFlag('inputId', {
defaultCountry: 'US',
value: '1234567890',
});
import React, { useState } from 'react';
import InFlagReact from 'inflag/dist/inflag-react.js';
import 'inflag/dist/style.css';
const App = () => {
const [phone, setPhone] = useState('');
return (
<div>
<h1>Phone Input</h1>
<InFlagReact value={phone} onChange={setPhone} />
</div>
);
};
export default App;
To use the InFlag component with Turbo, you need to ensure that the initialization happens only once to prevent duplicate setups. Here's an example of how to set it up within a Turbo-enabled environment:
import InFlagTurbo from 'inflag-turbo';
import 'inflag/dist/style.css';
document.addEventListener('turbo:load', () => {
new InFlagTurbo('inputId', {
defaultCountry: 'US',
value: '1234567890',
});
});
- Make sure to call the initialization within the
turbo:load
event to ensure that it runs after Turbo loads the new content. - Avoid re-initializing the component on every Turbo load by managing its state (e.g., using a flag to check if it's already initialized).
You can customize the styles of the component by overriding the default CSS classes. Here are some common customization points:
.template {
padding-bottom: 10rem;
}
.phone-input-wrapper {
display: inline-block;
position: relative;
width: 100%;
}
.phone-input-flag {
width: 30px;
height: 20px;
margin-right: 10px;
border-radius: 3px;
position: absolute;
left: 10px;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
}
.phone-input-country {
padding-left: 50px;
height: 40px;
font-size: 16px;
width: 100%;
box-sizing: border-box;
vertical-align: middle;
}
.phone-input-dropdown {
position: absolute;
top: 100%;
left: 0;
background: white;
border: 1px solid #ddd;
width: 100%;
display: none;
z-index: 10;
box-sizing: border-box;
max-height: 200px;
overflow-y: auto;
}
.phone-input-dropdown.open {
display: block;
}
.phone-input-item {
padding: 10px;
cursor: pointer;
border-bottom: 1px solid #ddd;
}
.phone-input-item:hover {
background-color: #f0f0f0;
}
.phone-input-country-list {
max-height: 200px;
overflow-y: auto;
}
.phone-input-search {
padding: 10px;
border-bottom: 1px solid #ddd;
width: 100%;
box-sizing: border-box;
}
.pseudo-placeholder {
position: absolute;
top: 50%;
transform: translateY(-50%);
pointer-events: none;
color: rgba(0, 0, 0, 0.4);
font-family: inherit;
white-space: nowrap;
vertical-align: middle;
}
MIT
This project was made possible with the financial support of Randevu.