Dynamically Render Components in React Based on Conditions
ReactJS is a popular JavaScript library for building user interfaces. One of the powerful features of React is its ability to dynamically render components based on certain conditions. This allows you to create flexible and reusable components that can adapt to different scenarios.
1. Utilizing useState
and useEffect
One approach to dynamically rendering components in React is through the useState
and useEffect
hooks.
useState
allows you to create and update state variables, while useEffect
allows you to perform side effects in response to state changes.
import React, { useState, useEffect } from "react";
const Input = ({ value, onChange }) => {
return ;
};
const Form = () => {
const [inputList, setInputList] = useState([""]);
useEffect(() => {
setInputList(["Apple", "Mango", "Carrot"]);
}, []);
const onAddBtnClick = (event) => {
setInputList([...inputList, ""]);
};
const onSubmit = () => {
// Handle the form submission
};
return (
);
};
export default Form;
In this example, the useState
hook is used to create a state variable called inputList
that holds an array of input values.
useEffect
is used to initialize the inputList
state with a predefined array of values (e.g., ["Apple", "Mango", "Carrot"]).
The onAddBtnClick
handler adds an empty input field to the form, and the onSubmit
handler processes the form data.
2. Using Refs to Capture Form Values
Another approach for dynamically rendering components and capturing form values is by using refs. Refs allow you to access and manipulate DOM elements directly within your React components.
import React, { useState, useRef } from "react";
const Input = React.forwardRef((props, ref) => {
return ;
});
const Form = () => {
const inputRefs = useRef([]);
const [inputList, setInputList] = useState([""]);
const onAddBtnClick = () => {
setInputList([...inputList, ""]);
};
const onSubmit = (event) => {
event.preventDefault();
const values = inputRefs.current.map(input => input.value);
console.log(values);
};
return (
);
};
export default Form;
In this example, we use a forwardRef
to create a custom Input
component that accepts a ref.
We then create an array of refs using useRef
to store references to each input element in the form.
When the form is submitted, we can access the values of all the input fields using the refs.