Components are like pure javascript functions that help make the code easy by splitting the logic into reusable independent code.
Components as functions
test.jsx
import React from 'react';
import ReactDOM from 'react-dom';
function Hello() {
return <h1>Hello, from Viastudy Tutorials!</h1>;
}
const Hello_comp = <Hello />;
export default Hello_comp;
We have created a function called Hello that returned h1 tag as shown above. The name of the function acts as an element, as shown below:
const Hello_comp = <Hello />;
export default Hello_comp;
The Component Hello is used as an Html tag, i.e., <Hello /> and assigned to Hello_comp variable and the same is exported using export.
Let us now use this component in index.js file as shown below:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Hello_comp from './test.jsx';
ReactDOM.render(
Hello_comp,
document.getElementById('root')
);
Here is the output in the browser:
Class as Component
Here is an example that uses a class as a component.
test.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class Hello extends React. Component {
render() {
return <h1>Hello, from Viastudy Tutorials!</h1>;
}
}
export default Hello;
We can use Hello component in index.js file as follows:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './test.jsx';
ReactDOM.render(
<Hello />,
document.getElementById('root')
);
The Component Hello is used as an Html tag i.e., <Hello />.
Here is the output of the same.
No comments:
Post a Comment