Reputation: 1187
I have a series of TextInput components that are dynamically generated based on the number of entries in a map. I am trying to set my state for each TextInput independently, but can't quite figure it out. Here is my code:
<View style={{ flex: 1 }}>
<ScrollView contentContainerStyle={{ paddingVertical: 20 }}>
{ostDataPoints.map(({ ostDPID, ostDPName, ostDPUOM }) => (
<Card title={`${ostDPName}(${ostDPUOM})`} key={ostDPID} >
<Text style={{ marginBottom: 10 }}>
Test Name: {ostDPID}
</Text>
<Text style={{ marginBottom: 10 }}>
Test Type: {ostDPUOM}
</Text>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={(text) => this.setState({ text })}
value={this.state.text}
/>
<Button
backgroundColor="#03A9F4"
title="VIEW NOW"
onPress={() => {
alert("hi");
}}
/>
</Card>
))}
</ScrollView>
</View>
I want to do something like this (from react):
handleTextChange = (event) => {
this.setState({
[event.target.name]: event.target.value
})
}
Is there a way that I can set this event.target.name value in react native?
Upvotes: 1
Views: 3125
Reputation: 173
You can use an id or name props to identify what input is changing. The following code for example:
On CodeSandbox
index.js
import React from "react";
import ReactDOM from "react-dom";
import MyInput from "./MyInput";
import "./styles.css";
const items = [{ name: "first" }, { name: "second" }, { name: "third" }];
class App extends React.Component {
onTextChange(id, value) {
console.log(id, value);
}
render() {
return (
<ul>
{items.map(item => (
<li>
<MyInput
name={item.name}
textChange={(id, value) => this.onTextChange(id, value)}
/>
</li>
))}
</ul>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
MyInput.js
import React from "react";
export default class MyInput extends React.Component {
textChange(event) {
this.props.textChange(this.props.name, event.target.value);
}
render() {
return (
<input
type="text"
name={this.props.name}
onChange={e => this.textChange(e)}
{...this.props}
/>
);
}
}
Upvotes: 3