AlyaKra
AlyaKra

Reputation: 566

React : Get states of an input

I'm using react-intl-tel-input for react to create an input with countries.

The change for the values occurs for both the input and the country, but I can't find where the state is saved, as I would want to send them to my database later.

I tried creating my own handleChange but it didn't turn out as I wanted. Any ideas about how to get or set the states ?

Code ( Comments are what I tried ):

https://codesandbox.io/s/trusting-keldysh-h32qh?file=/src/App.js

import "./styles.css";
import React, { useEffect, useState } from "react";
import IntlTelInput from "react-intl-tel-input";
import "react-intl-tel-input/dist/main.css";

export default function App() {
  // const [input, setInput] = useState("");

  // const handleChange = (event) => {
  //   setInput(event.target.value);
  //   console.log(event);
  //  };

  return (
    <div className="App">
      <IntlTelInput
        containerClassName="intl-tel-input"
        inputClassName="form-control"
        preferredCountries={["tw"]}
        //onchange={handleChange}
      />
    </div>
  );
}

Upvotes: 0

Views: 859

Answers (2)

Subha
Subha

Reputation: 580

Please try this

import "./styles.css";
import React, { useEffect, useState } from "react";
import IntlTelInput from "react-intl-tel-input";
import "react-intl-tel-input/dist/main.css";

export default function App() {
  return (
    <div className="App">
      <IntlTelInput
        containerClassName="intl-tel-input"
        inputClassName="form-control"
        preferredCountries={["tw"]}
        customPlaceholder={(num, country) => {
          console.log(country.name, country.dialCode, country.areaCodes);
        }}
        onPhoneNumberChange={(b, n, c, number) => {
          console.log(number);
        }}
      />
    </div>
  );
}
  • Official docs link
  • Link to official playground to test all props in realtime without coding

The 3rd argument in the onPhoneNumberChange prop marked as c in my code will also give you country details. The reason I did not choose the country code from here is when a user selects a flag at the end after inputting the number the country details are not captured in this onPhoneNumberChange prop.

Upvotes: 1

Priyank Kachhela
Priyank Kachhela

Reputation: 2635

Accourding to docs,

onPhoneNumberChange -> Optional validation callback function. It returns validation status, input box value and selected country data.

onSelectFlag -> Allow main app to do things when a country is selected.

Here is example link

Upvotes: 0

Related Questions