DIE SQUAD
DIE SQUAD

Reputation: 11

How to put an input into an array and display it

const [array, setArray] = useState([])


return (
  <input onChange={(event)=> setArray(event.target.value)} />

  <p>{array}</p>
);

Sorry, i have no code example that i can show you. however the question is understandable. I want an input from a user and store it into an array, after that, i display it. Can you please answer it in a ReactJs way.

I've tried putting state hooks, and i haven't figure it out, on how to display it. The thing i want is i want the input to be store in the variable as a string and display it. Somepeople told me that i should use the .map() method, but i do not know how to implement it in my code.

Upvotes: 0

Views: 684

Answers (4)

Ram Sai Meghnadh
Ram Sai Meghnadh

Reputation: 50

This is just a quick way to get what you want.

You can also use spread syntax which is recommended way to update the reference of Array.

In your case, setArray(event.target.value) won't help, because setArray() expects a Array but event.target.value is just an string.

So take a look at the below code snippet which takes a temporary array and adds it to your state variable. Because updating array means two things

  1. Updating elements in array ( add, delete, modify elements )
  2. Updating the reference of array.

Since you want to display the array on UI. It's reference also has to be updated along with value, so that react knows and React's DOM will be updated with new Array value and UI will be refreshed.

const [array, setArray] = useState([])


pushIntoArray(value) {
    let tempArray = [];
    tempArray.push(value);
    setArray(tempArray);
}

return (
  <input onChange={(event)=> pushIntoArray(event.target.value)} />

  <p>{array}</p>
);

So, tempArray helps to get new reference each time.

You can also use spread syntax which is recommended way to update the reference of Array.

Upvotes: 1

Mallikarjun M G
Mallikarjun M G

Reputation: 609

If I understand this way,here it is

import React, { useState } from "react";
//import uid to get unique id's 
import { v1 as uuid } from "uuid";

import "./styles.css";

export default function App() {
// Hold array state(inputs)
  const [array, setArray] = useState([]);

  return (
    <div>
       //Update the array on entering inputs
      <input onChange={(e) => setArray((pre) => [...pre, e.target.value])} />
      // Display Input values
      <div>
        {array.length > 0 && array.map((text) => <p key={uuid()}>{text} </p>)}
      </div>
    </div>
  );
}

Upvotes: 2

devryan
devryan

Reputation: 31

import * as React from 'react';
import './style.css';

export default function App() {
  const [array, setArray] = React.useState([]);
  const [string, setString] = React.useState('');
  return (
    <div>
      <input onChange={(e) => setString(e.target.value)} />
      <button onClick={() => setArray((prevState) => [...prevState, string])}>
        Enter
      </button>
      <br />
      {array}
    </div>
  );
}

Am not sure this might be correct way to do it . Use One piece of state to store string and then push with a button atleast that how a real scenario would look like Look at this PEN might help https://stackblitz.com/edit/react-ts-hgqbmw?file=App.tsx

Upvotes: 0

Billy
Billy

Reputation: 21

Whatever you pass into setArray() will become the new value of array. Currently your onChange function will not add the target value into the array, it will replace it entirely. To add the value into array you can use spread syntax to create a new array which will include all the existing values, and the new value you want to add. Then pass that into the setArray(), instead of just the latest value from your input: <input onChange={(event) => setArray([...array, event.target.value])} />

To display the values from your array you could use .map() to put each value in a paragraph element: {array.length ? array.map(value => <p>{value}</p>) : null}

The above code uses a ternary operator to check if there are any values in the array. If there are more than 0 elements in the array, the array.map(...) method returns a paragraph element for each element in the array. If there are no elements in the array the above line will return null, which will render nothing to the DOM.

Upvotes: 0

Related Questions