Writing Component from scratch in JSX

Writing Component from scratch in JSX

Day 2 of 100 days of MERN Development

JavaScript XML

is a language in which HTML can be written in Javascript. A developer who knows HTML can easily write JSX following three simple rules.

  • Replace class with className.

for eg. navbar in bootstrap

<div className="nav"> </div>
  • inline styling style="backgroundcolor: black; color: white" is replaced with style={{backgroundcolor: 'black', color: 'white' }

  • JavaScript objects are to be included in {}.

import React from 'react';

class App extends React.Component {
    const article_no = 2;

    render () {
        return <p> This is my article number {article_no}. </p>
    }
}

export default App;

How JSX is rendered in Browser

let's start with creating a react project

npx create-react-app youtube_frontend
cd startup_college
rmdir src/App.test.js 
rmdir src/setupTests.js

Component Reusability

If we have to code the Youtube frontend then we break down components into SearchBar, PlayingVideo, and RecommendedVideos. Let's dive into coding SearchBar from scratch.

import React from 'react';

class SearchBar extends React.component {
    super(props) {
        state = {
            term: ''
        }
    }

   const onFormSubmit = (event) => {
        event.preventDefault();
        this.setState( term : event.target.value)

    }

   render () {
      <div className="search-bar ui segment">
        <form className="ui form" onSubmit={onFormSubmit}>
            <div className="field">
                <label>Video Search</label>
                <input 
                    type="text"
                    value={this.state.term}
                    onChange={(event) => this.setState( term : event.target.value)}
                />
            </div>
        </form>
    </div>
   }
}

export default SearchBar;

Now, this component can be used anywhere any number of times.

Component Nesting

Component Nesting is including a component in a component in laymen's terms.

import React from 'react';

class App extends React.Component {
    render () {
        return (<div className="ui container">
             <SearchBar />
       </div>);
    }
}

export default App;

In the next blog, we will understand What are states and props and the differences between them. Till then stay connected Twitter.