Display dynamic HTML form elements with array object having order configuration in it

Viewed 60

I am trying to generate HTML elements in dynamics way where, order of DOM element will displayed by object json config.

I have json object as

[{"orderDisplay" : 1, elementName: 'username'},
{"orderDisplay" : 2, elementName: 'password'},
{"orderDisplay" : 3, elementName: 'email'} ]

I have static DOM elements

for HTML

<input type='username' value='' />
<input type='password' value='' />
<input type='email' value='' />

with passed displayOrder, HTML element will be adjusted.

Any best method here, please comment.

thanks!

1 Answers

The list data structure is already in linear order.

So you could basically just have a controlled component for each input element and construct the element list.

/* Controlled Components */
function Username(props) {}
function Password(props) {}
function Email(props) {}

/* Parent Component (i.e. form) */
function Form(props) {
  const { elements } = props;
  return elements.map((e) => React.createElement(e))
}

function Page(props) {
  // TODO: generate elements list dynamically
  const elements = [Username, Password, Email];
  return (
    <Form elements={elements} />
  );
}
Related