0

I am pretty new to React, I have worked on react native before, so I am quite familiar with a framework. Basically I have an array of objects, lets say in contains 5 items. I populated views based on the amount of objects, so if there are 5 objects, my map function would populate 5 together with 5 inputs. My question is how can I get a value of each input? Here is my code:

array.map(map((item, index) => (
    <h1> item.title </h1>
    <input value={input from user} />
)
1
  • 1
    React docs provide good instructions on dealing with forms - reactjs.org/docs/forms.html Commented Aug 7, 2019 at 9:31

2 Answers 2

2

You have to use the state and update the value with onChange manually

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    value: ''
    }
  }
  handleInputChange(e) {
    this.setState({
        [e.target.name]: e.target.value
    });
  }
  render () {
    return (
      <div>
        <input value={this.state.value} onChange={(e) => {this.handleInputChange(e)}} />

      </div>
    )
  }
}

ReactDOM.render(<App />,  document.getElementById('app'))

Sign up to request clarification or add additional context in comments.

Comments

0

A quick solution would be to use an array for all the input values.

const Inputs = ({array}) => {
    const [inputs, setInputs] = useState([]);

    const setInputAtIndex = (value, index) => {
        const nextInputs = [...inputs]; // this can be expensive

        nextInputs.splice(index, 1, value);

        setInputs(nextInputs);
    }

    return (
        ...
        array.map((item, index) => (
            <div key={index}>
                <h1>{item.title}</h1>
                <input
                    value={inputs[index]}
                    onChange={({target: {value}) => setInputAtIndex(value, index)}
                />
            </div>
        )
        ...
    );
}

Keep in mind here that in this case every time an input is changed, the inputs state array is copied with [...inputs]. This is a performance issue if your array contains a lot of items.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.