I have created a question array set dynamically in which it has multiple textinput fields and i want to change height of the text input when the content size increases.
const[height,setHeight]=useState(44)
But i have multiple text input with multiline option
<TextInput multiline height={height} placeholderText={'Question 1'}/>
<TextInput multiline height={height} placeholderText={'Question 2'}/>
<TextInput multiline height={height} placeholderText={'Question 3'}/>
<TextInput multiline height={height} placeholderText={'Question 4'}/>
<TextInput multiline height={height} placeholderText={'Question 5'}/>
<TextInput multiline height={height} placeholderText={'Question 6'}/>
These textinput fields are dynamically created based on array
I would write conditions that set the height based on the string length.
Like so :
Create a custom componentL
const CustomInput = ({question}) => {
const[height,setHeight]=useState(5)
const [response, setResponse] = useState(')
useEffect(() => {
if(response.length < 10) setHeight(5)
if(response.length > 10 && textHeight < 20) setHeight(10)
if(response.length > 20 && textHeight < 30) setHeight(30)
},[height])
return (<TextInput
multiline
onChange={(e) => setResponse(e)}
height={height}
placeholderText={'Question 1'}
/>)
}
And then in the parent component:
const arrayOfQuestion = ['Question1','Question2','Question3','Question4']
const ParentComponent = () => {
return (
<View style={yourStyle}>
{arrayOfQuestion.map((q, i) => {
return CustomInput key={i} question={q} />
})}
</View>
)
}
(Putting index as a key for a mapped element will work but is not a good practice. Find something unique instead, like a question id if your backend sends one)