Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display react-native components array

Tags:

react-native

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>);
}
like image 320
user55093 Avatar asked Jan 09 '17 10:01

user55093


People also ask

How do you access array elements in react native?

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.

How do I render an array of elements in JSX?

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 do you render an array of objects in React functional component?

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.

How do I return an array in Reactjs?

The answer is, you use Array. map() in your component and return JSX elements inside the Array. map() callback function to render the UI.


2 Answers

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.

like image 182
Gui Herzog Avatar answered Oct 12 '22 00:10

Gui Herzog


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>);
 }
like image 5
Praveena Avatar answered Oct 12 '22 00:10

Praveena