DEV Community

Cover image for How to render array of components in React
collegewap
collegewap

Posted on • Originally published at codingdeft.com

How to render array of components in React

You might often encounter scenarios to render a list of components. In this article, we will see how to do the same.

Project setup

Create a react app using the following command:



npx create-react-app react-components-array


Enter fullscreen mode Exit fullscreen mode

Now install the react-icons package:



npm install react-icons


Enter fullscreen mode Exit fullscreen mode

This is required since we will be displaying a list of icons.

Creating an array of components

Consider the following component:



const Item = ({ value }) => {
  return <li>{value}</li>
}


Enter fullscreen mode Exit fullscreen mode

We can create a list of items as shown below:



const items = [<Item key={1} value={1} />, <Item key={2} value={2} />]


Enter fullscreen mode Exit fullscreen mode

Rendering the component array

Rendering an array of components is as easy as rendering variables in React:



import React from "react"

const Item = ({ value }) => {
  return <li>{value}</li>
}

const App = () => {
  const items = [<Item key={1} value={1} />, <Item key={2} value={2} />]

  return <ul>{items}</ul>
}

export default App


Enter fullscreen mode Exit fullscreen mode

All you need to do is add the array within the flower brackets {items}.

You can dynamically create the array of components as shown below:



import React from "react"

const Item = ({ value }) => {
  return <li>{value}</li>
}

const App = () => {
  const items = Array.from({ length: 10 }).map((_, index) => (
    <Item key={index} value={index + 1} />
  ))

  return <ul>{items}</ul>
}

export default App


Enter fullscreen mode Exit fullscreen mode

Storing components in an Array of objects and rendering them

Consider the following array:



import {
  MdOutlinePhone,
  MdOutlineFavorite,
  MdOutlineContactPhone,
} from "react-icons/md"

const menu = [
  {
    name: "Recents",
    icon: MdOutlinePhone,
  },
  {
    name: "Favorites",
    icon: MdOutlineFavorite,
  },
  {
    name: "Contacts",
    icon: MdOutlineContactPhone,
  },
]


Enter fullscreen mode Exit fullscreen mode

If you want to render the icons stored inside the array, you can do so by using the following code:



return menu.map(item => {
  return (
    <li key={item.name}>
      <item.icon /> {item.name}
    </li>
  )
})


Enter fullscreen mode Exit fullscreen mode

The complete code would be:



import React from "react"
import {
  MdOutlinePhone,
  MdOutlineFavorite,
  MdOutlineContactPhone,
} from "react-icons/md"

const menu = [
  {
    name: "Recents",
    icon: MdOutlinePhone,
  },
  {
    name: "Favorites",
    icon: MdOutlineFavorite,
  },
  {
    name: "Contacts",
    icon: MdOutlineContactPhone,
  },
]

const App = () => {
  return menu.map(item => {
    return (
      <li key={item.name}>
        <item.icon /> {item.name}
      </li>
    )
  })
}

export default App


Enter fullscreen mode Exit fullscreen mode

If you run the app now, you will see the following output:

list of icons

Top comments (2)

Collapse
 
marlo-bb profile image
ِMarlo Ber

import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import Swal from 'sweetalert2';

function Register() {
const [fullName, setFullName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');

const navigate = useNavigate();
const apiUrl = 'https://683da3f6199a0039e9e64a3e.mockapi.io/login'; 

const btnSubmit = async (e) => {
    e.preventDefault();
    if (!fullName || !email || !password || !confirmPassword) {
        Swal.fire("Error", "Please fill in all fields", "error");
        return;
    }

    if (password.length < 6) {
        Swal.fire("Error", "Password must be at least 6 characters", "error");
        return;
    }

    if (password !== confirmPassword) {
        Swal.fire("Error", "Passwords do not match", "error");
        return;
    }

    try {

        const res = await axios.get(apiUrl);
        const userExist = res.data.find(user => user.email === email);

        if (userExist) {
            Swal.fire("Error", "Email already used", "error");
            return;
        }


        const response = await axios.post(apiUrl, {
            fullName,
            email,
            password,
        });

        Swal.fire("Success", "Registration successful", "success");
        localStorage.setItem("user", JSON.stringify(response.data));
        navigate("/");
    } catch (err) {
        console.error(err);
        Swal.fire("Error", "Something went wrong. Please try again.", "error");
    }
};

return (
    <div className="flex justify-center items-center min-h-screen">
        <div className="w-full max-w-md p-6 bg-white rounded shadow">
            <div className="text-center mb-6">

                <h2 className="text-2xl font-bold">تسجيل الدخول</h2>
            </div>

            <form onSubmit={btnSubmit} className="space-y-4">
                <div>
                    <label className="block mb-1">Full Name</label>
                    <input
                        type="text"
                        value={fullName}
                        placeholder="Full Name"
                        onChange={(e) => setFullName(e.target.value)}
                        className="w-full px-4 py-2 border rounded"
                        required
                    />
                </div>

                <div>
                    <label className="block mb-1">Email</label>
                    <input
                        type="email"
                        value={email}
                        placeholder="Email Address"
                        onChange={(e) => setEmail(e.target.value)}
                        className="w-full px-4 py-2 border rounded"
                        required
                    />
                </div>

                <div>
                    <label className="block mb-1">Password</label>
                    <input
                        type="password"
                        value={password}
                        placeholder="Password"
                        onChange={(e) => setPassword(e.target.value)}
                        className="w-full px-4 py-2 border rounded"
                        required
                    />
                </div>

                <div>
                    <label className="block mb-1">Confirm Password</label>
                    <input
                        type="password"
                        value={confirmPassword}
                        placeholder="Confirm Password"
                        onChange={(e) => setConfirmPassword(e.target.value)}
                        className="w-full px-4 py-2 border rounded"
                        required
                    />
                </div>

                <button
                    type="submit"
                    className="w-full bg-blue-500 text-white py-2 rounded hover:bg-red-600 transition"
                >
                    Register
                </button>
            </form>
        </div>
    </div>
);
Enter fullscreen mode Exit fullscreen mode

}

export default Register;

Collapse
 
mariaalba profile image
Maria

import React, { useState } from 'react';
import axios from 'axios';
import Swal from 'sweetalert2';
import { Link, useNavigate } from 'react-router';

export default function Signin() {
const [name, setName] = useState('');
const [password, setPassword] = useState('');
const navigate = useNavigate();

const handleSignin = async () => {
if (!name.trim() || !password.trim()) {
Swal.fire('خطأ', 'الرجاء إدخال الاسم وكلمة المرور.', 'error');
return;
}

try {
  const res = await axios.get('url');
  const users = res.data;

  const matchedUser = users.find(
    (user) => user.name === name && user.password === password
  );

  if (matchedUser) {

    localStorage.setItem('user', JSON.stringify(matchedUser));

    Swal.fire('تم بنجاح', 'مرحباً بعودتك!', 'success').then(() => {
    navigate('/');
    });

  } else {
    Swal.fire('خطأ', 'الاسم أو كلمة المرور غير صحيحة.', 'error');
  }
} catch {
  Swal.fire('خطأ', 'حدث خطأ ما، حاول مرة أخرى لاحقاً.', 'error');
}
Enter fullscreen mode Exit fullscreen mode

};

return (


Full Name
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Full Name"
className='border-1 rounded-2xl w-80 p-2'
/>
     <label>Password</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Password"
              className='border-1 rounded-2xl w-80 p-2'
            />

            <button
               onClick={handleSignin}
                className="btn btn-soft btn-primary"> Sign  In</button>


          <div className="mt-4 text-sm text-gray-600"> Don't  have an account?
            <Link to="/signup"><button className="btn btn-soft btn-accent">Sign Up</button></Link>
         </div>

</div>

);
}