Implementing a dynamic form with dynamic field styling based on user input in Next.js involves several steps. Here's a basic guide to accomplish this:
create-next-app
.bashnpx create-next-app my-dynamic-form
cd my-dynamic-form
jsx// components/DynamicForm.js
import { useState } from 'react';
const DynamicForm = () => {
const [fields, setFields] = useState([]);
const addField = () => {
setFields([...fields, { value: '' }]);
};
const removeField = (index) => {
const updatedFields = [...fields];
updatedFields.splice(index, 1);
setFields(updatedFields);
};
const handleChange = (index, e) => {
const updatedFields = [...fields];
updatedFields[index].value = e.target.value;
setFields(updatedFields);
};
return (
<form>
{fields.map((field, index) => (
<div key={index}>
<input
type="text"
value={field.value}
onChange={(e) => handleChange(index, e)}
/>
<button type="button" onClick={() => removeField(index)}>
Remove
</button>
</div>
))}
<button type="button" onClick={addField}>
Add Field
</button>
<button type="submit">Submit</button>
</form>
);
};
export default DynamicForm;
jsx// components/DynamicForm.js
import { useState } from 'react';
const DynamicForm = () => {
const [fields, setFields] = useState([]);
const addField = () => {
setFields([...fields, { value: '' }]);
};
const removeField = (index) => {
const updatedFields = [...fields];
updatedFields.splice(index, 1);
setFields(updatedFields);
};
const handleChange = (index, e) => {
const updatedFields = [...fields];
updatedFields[index].value = e.target.value;
setFields(updatedFields);
};
return (
<form>
{fields.map((field, index) => (
<div key={index}>
<input
type="text"
value={field.value}
onChange={(e) => handleChange(index, e)}
style={{
backgroundColor: field.value.length > 10 ? 'red' : 'white',
}}
/>
<button type="button" onClick={() => removeField(index)}>
Remove
</button>
</div>
))}
<button type="button" onClick={addField}>
Add Field
</button>
<button type="submit">Submit</button>
</form>
);
};
export default DynamicForm;
DynamicForm
component into your Next.js pages.jsx// pages/index.js
import DynamicForm from '../components/DynamicForm';
const Home = () => {
return (
<div>
<h1>Dynamic Form Example</h1>
<DynamicForm />
</div>
);
};
export default Home;
With these steps, you should have a dynamic form in your Next.js application where field styling changes based on user input. Adjust the styling logic according to your requirements.