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.
JavaScript
x
46
46
1
import { useState } from "react";
2
import "./styles.css";
3
4
const App = () => {
5
const [text, setText] = useState("");
6
const [data, setData] = useState([]);
7
8
const handleSubmit = (e) => {
9
e.preventDefault();
10
setData([data, text]);
11
setText("");
12
};
13
const reverseNumber = (e, each) => {
14
return each.split('').reverse().join('')
15
}
16
17
18
return (
19
<div>
20
<form onSubmit={handleSubmit}>
21
<input
22
placeholder="magic..."
23
value={text}
24
onChange={(e) => setText(e.target.value)}
25
type="number"
26
/>
27
<button disabled={!text} type="submit">
28
Add
29
</button>
30
</form>
31
32
<div className="content">
33
{data.length > 0 &&
34
data.map((each, index) => {
35
return <h3 key={index}
36
onClick={e => reverseNumber(e, each)}
37
>{each}
38
</h3>;
39
})}
40
</div>
41
</div>
42
);
43
};
44
45
export default App;
46
Advertisement
Answer
Hey You want to do something like this for easie.
JavaScript
1
49
49
1
import { useState } from "react";
2
import "./styles.css";
3
4
const App = () => {
5
const [text, setText] = useState("");
6
const [data, setData] = useState([]);
7
8
const handleSubmit = (e) => {
9
e.preventDefault();
10
setData([data, text]);
11
setText("");
12
};
13
const reverseNumber = (index, item) => {
14
item = item.split('').reverse().join('')
15
let neWData = [data];
16
newData[index] = item;
17
setData(newData)
18
}
19
20
21
return (
22
<div>
23
<form onSubmit={handleSubmit}>
24
<input
25
placeholder="magic..."
26
value={text}
27
onChange={(e) => setText(e.target.value)}
28
type="number"
29
/>
30
<button disabled={!text} type="submit">
31
Add
32
</button>
33
</form>
34
35
<div className="content">
36
{data.length > 0 &&
37
data.map((each, index) => {
38
return <h3 key={index}
39
onClick={e => reverseNumber(index, each)}
40
>{each}
41
</h3>;
42
})}
43
</div>
44
</div>
45
);
46
};
47
48
export default App;
49