Home > Blockchain >  Is it possible to write this a shorter way in React using onClick?
Is it possible to write this a shorter way in React using onClick?

Time:06-26

Right now, my code is working as intended, but I wanted to know if there was a shorter way of writing this. I'm using speaktts in React which consists of a const of what I want the text to be spoken through the text to speech. I have a function to handleClick and then the user would have to click on the button to hear the word. If the user clicks on the sound emoji, they will get to hear apple, banana, and carrot. Is there any way that I can make this shorter?


import React from "react";
import Speech from "speak-tts";

function Alphabet() {
  const [say1] = React.useState("apple");
  const [say2] = React.useState("banana");
  const [say3] = React.useState("carrot");
  const speech = new Speech();
  speech
    .init({
      lang: "en-US",
      rate: 0.4,
    })
    .then((data) => {
      console.log("Speech is ready, voices are available", data);
    })
    .catch((e) => {
      console.error("An error occured while initializing : ", e);
    });

  const handleClick1 = () => {
    speech.speak({
      text: say1,
    });
  };

  const handleClick2 = () => {
    speech.speak({
      text: say2,
    });
  };

  const handleClick3 = () => {
    speech.speak({
      text: say3,
    });
  };
  return (
    <>

          <h2>Apple</h2>
          <button
            value="Apple"
            onClick={handleClick1}
            alt="click here for pronounciation"
            className="buttonSound"
          >
                       
  • Related