Tuesday, November 23, 2021

Ninja - React Basic 2 - Component

Component


Let's have this structure

App.js

Navbar.js

BlogDetails.js

Sidebar.js

Categories.js

Tags.js

To Create  a new component - create new js file, better to have inside folder

create "component" folder inside "src" folder

create "Navbar.js"

src/component/Navbar.js


create code

rcc tab


will generate

------------------------

import React, { Component } from 'react';


class Navbar extends Component {

    render() {

        return (

            <div>            

            </div>

        );

    }

}


export default Navbar;


let's write some code block


class Navbar extends Component {

    render() {

        return (

            <nav className="navbar">

                <h1>Dojo blog</h1>

               <div className="links">

                    <a href="/">Home</a>

                    <a href="/create">New Blog</a>

                </div> 

            </nav>

        );

    }

}


Now let's import and use, inside App.js

once you import, you can nest it inside App.js


import Navbar from './component/Navbar'


add self close Navbar tab just above content

 <Navbar />

 

 

Code looks like

-------------


import logo from './logo.svg';

import './App.css';

import Navbar from './component/Navbar'


function App() {

  return (

    <div className="App">

      <Navbar />

      <div className="content">

        <h1>App Component</h1>

      </div>

    </div>

  );

}


export default App;



-------------


Now you can see, Nav bar loaded

http://localhost:3000/


Now let's  create a new component for "Home" page

create home.js file and continue above steps


home.js

rcc tab


------------------------------------------

import React, { Component } from 'react';


class Home extends Component {

    render() {

        return (

            <div> 

            </div>

        );

    }

}


export default Home;



--------------------------------------------


just a add dive tag with className home

add a h2 tag with homepage



import React, { Component } from 'react';


class Home extends Component {

    render() {

        return (

            <div className='home'>

                <h2>Home Page</h2>

            </div>

        );

    }

}


export default Home;



Now you can import in App.js --> 

just remove h1 tag and use <Home />



import logo from './logo.svg';

import './App.css';

import Navbar from './component/Navbar';

import Home from './component/Home';


function App() {

  return (

    <div className="App">

      <Navbar />

      <div className="content">

        <Home />

      </div>

    </div>

  );

}

export default App;

-----------------


Just like that, you can create multiple components , export them and import and use







 



No comments:

Post a Comment