This is the next episode of the ReactJS series, where we will be talking about “ReactJS Components”. Will go one at a time to learn things. So each post will talk about one chapter. If you have missed the previous posts , please follow them here:
Introduction to ReactJS
A quick overview of JSX
ReactJS Components:
ReactJS applications are made of components. Components are small reusable components which are usually written for a simple function.
Example of a simple component is :
var React = require(‘react’);
var ReactDOM = require(‘react-dom’);
var MyComponentClass = React.createClass({
render: function () {
return <h1>Hello world</h1>;
}
});
ReactDOM.render(
<MyComponentClass />,
document.getElementById(‘app’)
);
If you see the above code you will notice the variable MyComponentClass , this is a component here. This can be used multiple times .
You can also move this code to a separate JSX file (A file with .JSX extension) . Let’s look at the below example:
Create a file called App.jsx and paste the below code in that:
import React from ‘react’;
class App extends React.Component {
render() {
return (
<div>
<Header/>
<Content/>
</div>
);
}
}
class Header extends React.Component {
render() {
return (
<div>
<h1>Header</h1>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<h2>Content</h2>
<p>The content text!!!</p>
</div>
);
}
}
export default App;
If you already have the ReactJS setup (NOTE : If not go to the top links and configure it), let’s create some files to see the component in action. You can download the example file form the link below:
Once you have downloaded , you can see how the App.JSX file is reused in more than 1 index.html and Page1.html file as components. This is just example can be modified to suit your requirement.
App.JSX acts as a component here and main.js implements that in all the files and produces the index.js file in runtime. So, you will notice that in index.html we have mentioned script file as index.js instead of main.js. If you look at the config file you will know why we are using index,js file. Remember JSX is compiled to be used in React.
Conclusion:
So, this ends the ReactJS Components post and I hope you have gone a step further in React world. If any of these files did not make sense or you need any help if these files did not work, let me know. Will be happy to resolve them.
Keep reading and sharing….
Leave a Reply