We already learned a lot about the core fundamentals of React especially the JSX thing which is super important. As in previous I have mention that React is all about components you build your application with components and react is a library which makes these components so easy. Well till right now we only use one component, Time to change this, and for that, we will add a new folder and a file in the src folder of our project.
So let’s create a new folder named as Person. Inside that Person folder we will add a Person.js file. Now in that file, we want to create a component and we already did that. Most of the time you should use a different form of the component or of creating the component. A better function a simple javascript function because in its simplest form a component is just a function which returns some JSX.
Person
const person = () => { return <p> I am a Person</p>; };
This alone creates a valid function which we could use as a component but we also have to do two things.
We need to import React because keep in mind this JSX syntex is transformed to React.createElement() and to be able to call this method we need to import react from react package :
React
React.createElement()
import React from 'react'; // import React Package const person = () => { return <p> I am a Person</p>; };
yes! we dont need a componet class because we are not using a class which extends component instade we are creating a function.
component
we still need to export that function as default of its file.
import React from 'react'; const person = () => { return <p> I am a Person</p>; }; export default person; // export this function
Here we export this person const and which holds this function. Now we can start using this component in other files of our project. Let’s import this function in our src/App.js
const
... import Person from './Person/Person'; // import our own Person.js file ...
So, You could create your own component which we named <Person>, we can either use the opening and closing tag like this: <Person> <Person/> or since we dont nest anything between (Will cover that also in feature lessons). you can also use self closing tag like <Person />
<Person>
<Person> <Person/>
<Person />
import React, { Component } from 'react'; import './App.css'; import Person from './Person/Person'; class App extends Component { render() { return ( <div className="App"> <h1> Heading</h1> <p> Paragraph </p> <Person /> </div> ); } } export default App;
make sure your npm start is working in terminal so you can check your output on http://127.0.0.1:3000. So <Person /> is our only component getting used of course using it like this is already nice but what is the exact benefit of treating it like this instead of simply adding the code right into the App.js file. Let’s do more with this component to see that benefit in the next lesson.
npm start