Skip to content
Advertisement

how to reverse a clicked list item onclick in reactjs


I am getting numbers from the input field and rendering them below the input field one by one with the click of the button. So I want to know how can I reverse a text for a particular clicked item from the list.
Thank you.

import { useState } from "react";
import "./styles.css";

const App = () => {
  const [text, setText] = useState("");
  const [data, setData] = useState([]);

  const handleSubmit = (e) => {
    e.preventDefault();
    setData([...data, text]);
    setText("");
  };
  const reverseNumber = (e, each) => {
    return each.split('').reverse().join('')
  }
  

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          placeholder="magic..."
          value={text}
          onChange={(e) => setText(e.target.value)}
          type="number"
        />
        <button disabled={!text} type="submit">
          Add
        </button>
      </form>

      <div className="content">
        {data.length > 0 &&
          data.map((each, index) => {
            return <h3 key={index}
            onClick={e => reverseNumber(e, each)}
            >{each}
            </h3>;
          })}
      </div>
    </div>
  );
};

export default App;

Advertisement

Answer

Hey You want to do something like this for easie.

import { useState } from "react";
import "./styles.css";

const App = () => {
  const [text, setText] = useState("");
  const [data, setData] = useState([]);

  const handleSubmit = (e) => {
    e.preventDefault();
    setData([...data, text]);
    setText("");
  };
  const reverseNumber = (index, item) => {
    item = item.split('').reverse().join('')
    let neWData = [...data];
    newData[index] = item;
    setData(newData)
  }
  

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          placeholder="magic..."
          value={text}
          onChange={(e) => setText(e.target.value)}
          type="number"
        />
        <button disabled={!text} type="submit">
          Add
        </button>
      </form>

      <div className="content">
        {data.length > 0 &&
          data.map((each, index) => {
            return <h3 key={index}
            onClick={e => reverseNumber(index, each)}
            >{each}
            </h3>;
          })}
      </div>
    </div>
  );
};

export default App;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement