React.js for beginners
What is React ?
React is a Javascript library for building user interfaces. It is used to build single page applications. React is a declarative efficient and flexible for building reusable UI components. It was initially developed and maintained by facebook.
React Features
The important features of React.JS are as following :
- JSX ( Javascript XML )
- Components,
- One-way Data Binding,
- Virtual DOM,
- Simplicity ,
- Performance.
React JSX
JSX is a Javascript extension syntax used in React to write HTML and Javascript together. JSX provides to write HTML/ XML -(DOM) like tree structures in the same file where you write Javascript code .JSX tags have a tag name , attributes and childern.
Example
const App = () => {
return(
<div>
<h1>JSX</h1>
<h2 className=”main”>Text</h2>
</div>
)}
React Components
Component makes the task of building UIs much easier. Components are like functions that return HTML elements. Every React Component have their own structure, methods as well as APIs. They can be reusable as per you need.
React.js have mainly two types of Components. They are :
1 ) Functional Components
2 ) Class Components
Functional Components
Functional Components are simply Javascript functions that may or may not receive data as parameters. We can create a function that takes props as input and returns what shold be render. Here , Home is a Function Component.
function Home (){
return(
<h3> Hi, I am Sharmin.</h3>
)
}
Class Components
The Class Components are a little more complex than the functional Components . It requires you to extend from React. Component and create a render function which returns a React element. We can create a class that extends component and has a render function. The name of component should always start with a capital letter
Example
class Home extends React.component{
render(){
return (
<h3> Hi, I am Sharmin</h3>
)
}
}
React useState Hooks
The state is an updatable structure . React state is the heart of react component which is used to contain data or information about the component. It can change over time. The state object is where you store property values that belongs to the component when the state changes, the component re-renders.
To define a state, you have to first declare a default set of values for defining the components initial state.
Example
const App = () => {
const [count, setCount ] = useState(0);
return(
)
};
React Props
React allows us to pass information to a component using something called props stands for properties. React props are like function argument in Javascript and attributes in HTML. To send props into a component. The component receives the argument as a props object.
Example
const App = ({count}) => {
return(
<h1> {count.length} </h1>
)
};
React UseEffect Hooks
If you are familiar with React class life cycle methods. You can think of useEffect Hook as componentDidMount( ), componentDidUpdate( )and componentWillUnmount( ) combined. ( React.js Docs )
UseEffect is the most popular Hooks because it allows you to perform side effect in function components in useEffect use cases. Some common use cases of UseEffect are :
- Add an event listener for a button.
- Data fetching from API when component mounts.
- Perform an action when state or props change.
- Clean up event listeners when the component unmounts;
useEffect is used in place of a life cycle Method. It’s important to use Dependency arrays correctly to optimize our useEffect hook. One important use of these hooks is a prevent unnecessary re-renders even when nothing changes.
The useEffect Hook takes two arguments
useEffect( ()=> {
//code
}, [props, state] );
The first argument is a callback function that by default run after every render. The second argument is an optional dependency array that tells the hook to only callback if there is a change in a target state.
React Context
Context allows passing data through the component tree without passing props down manually at every level. In react application context is used to share data which can be considered global for React components tree and use that data where needed, such as the current authenticated user, theme etc. If you only want to avoid passing some props through many levels component composition is often a simpler solution than context.
React Context API
The React Context API is a component structure which allows us to share data across all levels of the problem of prop-drilling. The context API in react.
- React.createContext.
- Context.Provider
- Context.Consumer
- Class.ContextType.
Example
const themeContext= createContext();
const App = () => {
return(
<themeContext.Provider value=”btn btn-info”>
<Home/>
<themeContext.Provider>
React Hook Form
Form are very important part in any web application. A form can contain text fields, buttons, checkbox etc. React hook form give you form validation out of the box . You have to handle forms yourself in React. This brings about many complications like how to get form values, how to manage from state and how to validate a form on the fly and show validation messages.
Two types of form input in React. One is uncontrolled input and another is controlled input.
The uncontrolled input are like traditional HTML form inputs. We will use ‘ref’ to get the form values.
Controlled components have functions that govern the data passing into them on every onChange event, rather than grabbing the data only once when you click a submit button. This data is saved to state and updated with setState( ) method. This makes component have better controll over the form element.
import { useForm } from “react-hook-form”;
export default function App() {
const { register, handleSubmit, watch, formState: { errors } } = useForm(); const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input defaultValue=”test” {…register(“example”)} />
<input {…register(“exampleRequired”, { required: true })} />
{errors.exampleRequired && <span>This field is required</span>}
<input type=”submit” /> </form> ); }