I have an array of react native components and would like to display them all at once in a View however I keep getting the error
RawText [object object] must be wrapped in an explicit Component
and displaying it in a Text will not get the desired result, how do I go about it.
render()
{
var CompArray = new Array();
CompArray[0] = <TextInput placeholder="First Name"/>
CompArray[1] = <TextInput placeholder="Last Name"/>
var Components = CompArray.join();
return(<View>{Components}</View>);
}
Use square brackets to get the first element of an array in React, e.g. const first = arr[0]; . The array element at index 0 is the first element in the array. If the array is empty, an undefined value is returned.
To render multiple JSX elements in React, you can loop through an array with the . map() method and return a single element. In the next example, you will examine why you would want to add a unique key to a list of elements rendered by an array.
How we will render an Array of Objects? We will use the map function to access each object from the array. The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method.
The answer is, you use Array. map() in your component and return JSX elements inside the Array. map() callback function to render the UI.
One great way of creating an array of components is creating an array of data and using a map to transform them into components. This also avoids duplicating code.
To do this is easy:
const form = ['First Name', 'Last Name', 'Phone', 'Email', 'Etc']
const textInputComponents = form.map(type => <TextInput placeholder={type} />)
Them on render or return: call the array of components you just created:
render(){
<>{textInputComponents}</>
}
This is especially useful if your form/array is big, and you can even use it with an array of objects.
Your code is fine but you are doing one extra thing which is joining the array. You don't have to do that.
render()
{
var CompArray = new Array();
CompArray[0] = <TextInput placeholder="First Name"/>
CompArray[1] = <TextInput placeholder="Last Name"/>
return(<View>{CompArray}</View>);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With