Ben Aston Ben Aston - 1 month ago 5
React JSX Question

Rendering a ReactJS component in memory before placing it in the DOM

I have the concept of a tile in my application.

Tiles are dynamically loaded. They can then be initialized against a DOM element using an

init
method, with the tile taking care of rendering itself.

features/my-tile/tile.js

import contentsComponentFactory from './components/contents/factory'

const tile = {
init,
};

// `el` is a DOM element
function init(el) {
// Render a "contents" ReactJS component (see below) to the DOM - how?
// Is the following possible?
el.appendChild(contentsComponentFactory.create({ props }).render());
}

export default tile;


A tile has a component
contents
which renders the tile contents to the screen.

features/my-tile/components/contents/factory.js

const factory = {
create
};

function create(options) {
const component = Object.create(React.Component.prototype);

component.props = options.props;
component.state = { message: 'This is a tile' };
component.render = function() {
return <div>{this.state.message}</div>;
};

return component;
}

export default factory;


In AngularJS, in
init
I would render the contents in memory and insert the result into the DOM. Can I do this in ReactJS?

I am new to ReactJS and so I may be completely misunderstanding something.

lux lux
Answer

You should be able to utilize React.createElement to create the element in memory, and then ReactDOM.render() in order to insert it into the DOM.

const element = React.createElement('div', null, 'Hello, World!');
ReactDOM.render(element, document.getElementById('content'));

http://codepen.io/mikechabot/pen/PGXwxa?editors=1010

However, createElement doesn't return a native DOM element, but rather an instance of ReactElement. Not sure if this suits your needs.