Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
Using regex with react hooks

I am basically trying to save the phone number entered by the user without braces, spaces or dashes but I somehow fail to do that. I am calling the regex after submitting the form in handleSubmit function through the setting of state and it prints out (and renders) without any change. Any idea what went wrong?

import React, { useContext, useState, useEffect } from "react";
import DataContext from "../store/data-context";

function Form() {
  const [name, setName] = useState("");
  const [secName, setSecName] = useState("");
  const [tel, setTel] = useState("");
  const [note, setNote] = useState("");
  const [state, setState] = useState({
    name: "",
    secName: "",
    tel: "",
    note: "",
  });
  

  const { dispatchDataState } = useContext(DataContext);

  const handleSubmit = (e) => {
    e.preventDefault();
    setTel((tel)=>tel.replace(/[^+\d]+/g, ""))
    console.log(name);
    dispatchDataState({ type: "ADD_DATA", payload: state });
    setState(
      {
        name: "",
        secName: "",
        tel: "",
        note: "",
      }
    )
    console.log(state);
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>
          Jméno
          <input
            type="text"
            required
            value={state.name}
            onChange={(e) => setState({ ... state, name: e.target.value })}
          />
        </label>
        <label>
          Příjmení
          <input
            type="text"
            required
            value={state.secName}
            onChange={(e) => setState({ ... state, secName: e.target.value })}
          />
        </label>
        <label>
          Telefonní číslo
          <input
            type="text"
            required
            value={state.tel}
            onChange={(e) => setState({ ... state, tel: e.target.value })}
            
          />
        </label>
        <label>
          Poznámka
          <input
            type="text"
            value={state.note}
            onChange={(e) => setState({ ... state, note: e.target.value })}
          />
        </label>
        <input type="submit" value="Odeslat" />
      </form>
    </div>
  );
}

export default Form;
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!