M
M
mosikus2020-09-13 19:08:49
React
mosikus, 2020-09-13 19:08:49

How to create a new cell when filling in the input (data entry) and clicking on the button?

Hello. Let's say I have an object

const test = [
  { id: "1", name: "name1" },
  { id: "2", name: "name2" },
  { id: "3", name: "name3" },
  { id: "4", name: "name4" },
  { id: "5", name: "name5" },
  { id: "6", name: "name6" },
  { id: "7", name: "name7" },
  { id: "8", name: "name8" },
  { id: "9", name: "name9" }
];

and i take it out
class App extends React.Component {
  state = {
    search: ""
  };

  get test() {
    return test;
  }

  render() {
    return (
      <div>
        <div>
          {this.test.map((kef, i, a) => (
            <div>
              <div>name: {kef.name}</div>
              <div>id: {kef.id}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }
}

https://codesandbox.io/s/sharp-bartik-d6jju?file=/...
Well, it doesn't matter. I have a slightly different question, this is just an example. I'm without a back, but I would like to test it somehow, I would like to see it. Let's say I have 2-3 inputs in my application, the user fills them in and clicks the "create" button. And on one of the panels a cell with filled data appears. How can this be implemented? I thought just to do it on the states, but this is completely nonsense. And please correct the title of the question.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-09-13
@mosikus

function App(props) {
  const [ items, setItems ] = React.useState([...props.items]);
  const [ name, setName ] = React.useState('');

  const add = () => setItems([
    ...items,
    {
      id: 1 + Math.max(0, ...items.map(n => n.id)),
      name,
    },
  ]);

  return (
    <div>
      <div>
        <input onChange={e => setName(e.target.value)} />
        <button onClick={add}>add</button>
      </div>
      {items.map(n => (
        <div key={n.id}>
          {Object.entries(n).map(([ k, v ]) => <div>{k}: {v}</div>)}
        </div>
      ))}
    </div>
  );
}

K
Kirill Makarov, 2020-09-14
@kirbi1996

Using the spread operator settish, in order to add to the desired position, use the length of the array

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question