forked from JedWatson/react-select
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate1.js
81 lines (74 loc) · 2.05 KB
/
update1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import React, { useState, useContext, useReducer } from 'react';
// Define the initial state and reducer for form fields
const initialState = [];
const formReducer = (state, action) => {
switch (action.type) {
case 'ADD_FIELD':
return [...state, action.payload];
case 'UPDATE_FIELD':
return state.map(field => field.id === action.payload.id ? action.payload : field);
default:
return state;
}
};
// Context for form state
const FormContext = React.createContext();
const FormProvider = ({ children }) => {
const [state, dispatch] = useReducer(formReducer, initialState);
return (
<FormContext.Provider value={{ state, dispatch }}>
{children}
</FormContext.Provider>
);
};
// Form Designer Component
const FormDesigner = () => {
const { state, dispatch } = useContext(FormContext);
const addField = (type) => {
dispatch({
type: 'ADD_FIELD',
payload: { id: Date.now(), type, label: '', placeholder: '', required: false }
});
};
return (
<div>
<button onClick={() => addField('text')}>Add Text Field</button>
<button onClick={() => addField('email')}>Add Email Field</button>
{state.map(field => (
<div key={field.id}>
<input
type="text"
value={field.label}
onChange={(e) => dispatch({ type: 'UPDATE_FIELD', payload: { ...field, label: e.target.value }})}
placeholder="Label"
/>
</div>
))}
</div>
);
};
// Form Renderer Component
const FormRenderer = () => {
const { state } = useContext(FormContext);
return (
<form>
{state.map(field => (
<div key={field.id}>
<label>{field.label}</label>
<input type={field.type} placeholder={field.placeholder} required={field.required} />
</div>
))}
<button type="submit">Submit</button>
</form>
);
};
const App = () => (
<FormProvider>
<div>
<h1>Dynamic Form Builder</h1>
<FormDesigner />
<FormRenderer />
</div>
</FormProvider>
);
export default App;