I have three main components for a dashboard UI I'm working on (I'm a React beginner, coming from Angular): a sidebar, top nav, and a content container.
How would I split these into three separate UI components and call them in other components? I want to be able to do this:
<Sidenav /> <!-- sidenav component from Sidenav.js -->
<section className="content">
<Topnav /> <!-- top nav component from Topnav.js -->
<div className="wrapper container">
<!-- Content here -->
</div>
</section>
And also, how would you use the <div className="wrapper container"></div>
as a view for all content?
I'm using ES6 and the React Starterify app kit.
This is how I would do it (you'll notice I name all my component files .jsx
instead of .js
, though it doesn't matter either way. I've even seen people do Component.jsx.js
):
src/index.html
<html>
<head>
...
</head>
<body>
<script src="js/bundle.min.js"></script> <!-- I'm assuming you're using Browserify or similar to bundle the entire app into a single file -->
</body>
</html>
src/js/main.js
import React from 'react';
import {render} from 'react-dom';
import {Routes} from '../components';
render(Routes, document.body);
src/components/App.jsx
import React from 'react';
import Topnav from './Topnav';
module.exports = React.createClass({
displayName: 'App',
propTypes: {
children: React.PropTypes.shape({
props: React.PropTypes.object
})
},
render () {
return (
<section className="content">
<Topnav />
<div className="wrapper container">
{this.props.children}
</div>
</section>
);
}
});
{this.props.children}
will render the component that is handling the current route.
src/components/Topnav.jsx
...
Think of it the same way you would create grouping in an object-oriented language like Java. Components that belong with each other should go together. So, for example, if I had to write a Profile
component, that might look like:
-- src
-- components
-- profile
-- index.js // Used to export Profile
-- Profile.jsx // This would have the profile layout and be a parent to all other components in this folder
-- Address.jsx
-- Gravatar.jsx
-- ...