Automatically add # after clicking submit

Viewed 24

I am building a color generator and I noticed that if you just write the code (for example: C4C4C4) without adding "#" nothing happens.

I would like it to work even if the user forgets to add "#".

Perhaps by having the code add it after clicking "Submit".

function App() {
  const [color, setColor] = useState("");
  const [error, setError] = useState(false);
  const [list, setList] = useState(new Values("#C4C4C4").all(10));

  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      let colors = new Values(color).all(10);
      setList(colors);
    } catch (error) {
      setError(true);
      console.log(error);
    }
  };

  return (
    <>
      <Navbar />
      <section className="container">
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            value={color}
            onChange={(e) => setColor(e.target.value)}
            placeholder="#C4C4C4"
            className={`${error ? "error" : null}`}
          />
          <button className="btn" type="submit">
            Submit
          </button>
        </form>
      </section>
      <section className="colors">
        {list.map((color, index) => {
          return (
            <SingleColor
              key={index}
              {...color}
              index={index}
              hexColor={color.hex}
            />
          );
        })}
      </section>
      <Footer />
    </>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

2 Answers

You could do that in the change handler for the input. This will force the input to always start with #.

const handleChangeColor = (e) => {
  let value = e.target.value;
  if (value.length > 0 && !value.startsWith("#")) {
    value = "#" + value;
  }
  setColor(value);
}


<input
  ...
  ...
  onChange={handleChangeColor}
/>

Or after submit:

const handleSubmit = (e) => {
  e.preventDefault();
  try {
    let value = color;
    if (value.length > 0 && !value.startsWith("#")) {
      value = "#" + value;
    }
    let colors = new Values(value).all(10);
    setList(colors);
  } catch (error) {
    setError(true);
    console.log(error);
  }
};

You can use a function to check if the hex string starts with '#' or not. If the string already has a '#' then you can return that string or if it doesn't have a '#' then you can return the string concatenated with a '#' at the beginning. Here's an example of how you could do that:

function formatColorName(name) {
  if (name.startsWith("#")) {
    return name;
  } else {
    return `#${name}`;
  }
}

You would call this function in your submit handler before creating the new color.

  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      const colorToAdd = formatColorName(color);
      let colors = new Values(colorToAdd).all(10);
      setList(colors);
    } catch (error) {
      setError(true);
      console.log(error);
    }
  };

Here's a full example on codesandbox: Edit Color Getter

Related