user1547174 user1547174 - 3 months ago 19
React JSX Question

Uncaught Invariant Violation: Objects are not valid as a React child for HTML Form

I wrote a function to build an HTML form based on the keys and values of an object and I am trying to return the form in my

render
method. However, I keep getting the error:

ReactJs 0.14 - Invariant Violation: Objects are not valid as a React child


Here is my
createForm()
method:

createForm() {

const obj = {

}

const object_fields = resourceFields.fields;
let form = document.createElement('form');

_.forIn(object_fields, function(field_value, field_name) {


let div = document.createElement('div');
div.setAttribute('className', 'form-control');

let label = document.createElement('label');
label.setAttribute('htmlFor', 'name');
label.innerHTML = field_name;

let input = document.createElement('input');
input.setAttribute('className', 'form-control');
input.setAttribute('type', 'text');
input.setAttribute('ref', field_name);
input.setAttribute('id', field_name);
input.setAttribute('value', field_value);
input.setAttribute('onChange', '{this.handleChange}');

div.appendChild(label);
div.appendChild(input);
form.appendChild(div);

})

console.log(form) //this prints out fine

return form


}


Here is my
render()
method:

render() {
return (
<div>
{this.createForm()}
</div>
)
}


Does anyone know what might be happening? My form prints out in the console just fine... Thanks in advance!

Answer

You never manipulate actual DOM nodes when you're working with React. When you build your UI in the render function, the JSX markup is translated into plain JavaScript (React.createElement function calls), which builds a representation of the DOM.

So, in your case, you should return JSX in createForm, not a DOM element.