React Parent-Child Components

React Parent-Child Components

by Ifeanyi Omeata


#1. In the previous post, I showed you how we can use a react jsx component to dynamically display contents to our front-end view. This time we are going to use multiple components within a Parent component "App.js" to display contents. Let's create the Parent component "App.js" within our previous setup. We should also create child components and import them within the parent component.


import React from 'react';

import MyHeader from './components/MyHeader';
import Main from './components/Main';
import MyFooter from './components/MyFooter';

function App() {
  return (
    <div>
      <MyHeader />
      <Main />
      <MyFooter />
    </div>
  );
}

export default App;

image.png


#2. Next we need to setup the child components with the jsx contents we would like to display through the Parent component "App.js".


import React from 'react';

function MyHeader() {
  return <h1>Welcome to my React Profile Page.</h1>;
}

export default MyHeader;

image.png

import React from 'react';

function Main() {
  return (
    <div>
      <h2>Ifeanyi Omeata</h2>
      <p>I am a Software Developer and Cloud Engineer.</p>
      <p>My top 3 front-end tools are:</p>
      <ol>
        <li>React</li>
        <li>Angularjs</li>
        <li>Vuejs</li>
      </ol>
    </div>
  );
}

export default Main;

image.png

import React from 'react';

function MyFooter() {
  return <p>Copyright &copy; 2021. Ifeanyi Omeata.</p>;
}

export default MyFooter;

image.png


#3. Next we need to ensure that our parent component "App.js" is imported into the index.js file, and is also rendered to the front-end page.


import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

image.png


#4. Next, remember the index.html page should be setup to indicate where to display the components (the Node with id="root"), it receives from the index.js file.


<html>
  <head>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div id="root"></div>
    <script src="index.pack.js"></script>
  </body>
</html>

image.png


#5. Finally, our page should look something like this. Take note of the Child components within the Parent component.


image.png image.png


#End


Hope you enjoyed this! :) Follow me for more contents...


Get in Touch:
ifeanyiomeata.com

Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2021