Created
May 25, 2021 14:13
-
-
Save raghavddps2/f29d43992930ffc175b3605d9ca40355 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import logo from './logo.svg'; | |
| import './App.css'; | |
| import React, { useState } from 'react'; | |
| function App() { | |
| const [tweets,setData] = useState([""]) | |
| const onclick = (e) => { | |
| const newData = [...tweets,""] | |
| setData(newData) | |
| } | |
| const onClickSumbit = (e) => { | |
| //send data to server. | |
| console.log(tweets) | |
| } | |
| const handleChange = (e) => { | |
| let changedData = e.target.value | |
| tweets[e.target.name-1] = changedData | |
| } | |
| const elements = [] | |
| for(let i=1;i<=tweets.length;i++){ | |
| elements.push( | |
| <div><textarea className="style1" name={i} onChange={handleChange} keys={i}></textarea></div>) | |
| } | |
| return ( | |
| <div className="App"> | |
| <h1>Ineffcient Twitter Design!</h1> | |
| {elements} | |
| <br></br> | |
| <button key="button" onClick={onclick}>+</button> | |
| <br></br><br></br> | |
| <button key="button" onClick={onClickSumbit}>Submit</button> | |
| </div> | |
| ) | |
| } | |
| export default App; |
Author
Yes, got it. Will use spread syntax from now on.
Author
Thank you :)
There are two ways to access an obj key: obj[key] & obj.key. When it's a variable try to use obj.key so inside handleChange:
var index = e.target.name-1;
tweets.index = changedData;
Use tweets['index'] only if its an absolute value, dot operator is usually preferred. I don't know exactly if it's followed in all places but strictly in my prev internship.
Author
Okay, I will also follow that. It's actually kind of better I also think.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use this for updating state
setData(prevData=>{
...prevData,
newData
});