Reputation: 55769
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.
Upvotes: 2
Views: 2608
Reputation: 1
This seems a pretty complicated way to do things in AngularJS, maybe you should rethink your design?
It's even worse in React, are you intending on bypassing ReactDOM and inserting it manually?
I'd recommend at least going through the React tutorial before you attempt this.
Upvotes: 0
Reputation: 8446
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.
Upvotes: 1