I have a "container" react component which contains other react components. I want to save the "container" component (with its children) in mongodb a then get it from there. What is the best practice to do it? (user will add and edit those components in the container)
There are a number of ways to accomplish this. From what you describe, I would imagine making a JSON which 'describes' the component state. This structure can be up to you, but I have done things similar to:
{
title: 'Foo',
children: [{
title: 'c1',
component: 'Header',
description: 'c1 description'
}, {
title: 'c2',
component: 'Article',
description: 'c2 description'
}]
}
And just created custom render methods to dynamically populate children.
EDIT: I added component to the children. This allows you to identify which component to use. You will need to create something that converts this string into a reference to the actual component before rendering. Example below:
const fromMongo = {
title: 'Foo',
children: [{
title: 'c1',
component: 'Header',
description: 'c1 description'
}, {
title: 'c2',
component: 'Article',
description: 'c2 description'
}]
}
const Header = p => (
<header>{p.title}</header>
)
const Article = p => (
<article>{p.title}</article>
)
const components = {
Header,
Article,
}
class App extends React.Component {
componentWillMount () {
fromMongo.children.map(d => (
d.component = components[d.component]
))
}
render () {
return (
<div>
{fromMongo.children.map(d => (
<d.component title={d.title} />
))}
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('app')
)
header {
background-color: blue;
}
article {
background-color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With