Oct. 1, 2024, 11:22 a.m.
ReactJs

React function component

There are 3 files we will be working with mostly when building a stand alone React app.

  • App.js
    This file contains the main React component.
    This is were we will place our React functions and class component.
  • index.js
    This file contains the link to the Dom element.
    This file render the React component to the HTML page
  • index.html
    This is the page that display the React component.
    This file is rendered to the browser.

But for this tutorial we will be working with the App.js file

Create a React component

React component is a JavaScript function or class.

I will be creating a React component using a React function. React component can also be created using a React class. Whichever one you choose to use is fine, the choice is a matter of preference.

For the record, must developer prefer to use the React function component in their coding.


Open file App.js and delete all the codes after the import statement.

Leave only the import statement and export statement

Anything in between delete it out. We are going to be inputting our own code into this place.

//App.js


function App(props){
return <h1>Hello World</h1>
}
export default App;


Example 2: React form input

//App.js


import './App.css';
import { useState } from 'react';

//use {useState} hook to update every input..
function MyInfo(){
  const [inputName, setinputName] = useState("");

  const handleSubmit = (event) => {
    
    /* event.preventDefault(): prevent browser from executing the default action
    associated with the event. It tell browser not to perform it default behavior
    for the event
    */
    
    event.preventDefault();
    alert(`My name is: ${inputName}`)
  }

  //add event handler onSubmit attribute for the form
  return (

<form onSubmit={handleSubmit}>
<label>Enter your name:
<input type="text" value={inputName} onChange={(e) => setinputName(e.target.value)} />
</label><input type="submit" />
</form>
    
  )
}

export default MyInfo;

AUTHOR
...
Git Puppy's

Built with love, for the love of the community. Git Puppy's making coding friendlier since 90's.

Hi there, I take request for tutorials and I create them for free so feel FREE to reach out.

Latest Articles

React function component

There are 3 files we will be working with mostly when building a stand alon