What is the syntax of ReactJS?
ReactJS Syntax
ReactJS, developed by Facebook, is a powerful JavaScript library used for building dynamic and interactive user interfaces, especially for single-page applications (SPAs). Understanding React’s syntax is fundamental to leveraging its full potential. Here’s a comprehensive overview of ReactJS syntax, covering its core concepts and practical examples.
1. JSX (JavaScript XML)
JSX is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. It makes the code more readable and easier to write by visually representing the UI structure.
-
Basic JSX Syntax:
const element = <h1>Hello, World!</h1>;
-
Embedding JavaScript Expressions:
const name = 'Alice'; const element = <h1>Hello, {name}!</h1>;
-
JSX Must Have One Parent Element:
// Incorrect const element = ( <h1>Hello</h1> <h2>World</h2> ); // Correct const element = ( <div> <h1>Hello</h1> <h2>World</h2> </div> );
2. Components
React applications are built using components, which are the building blocks of the UI. Components can be functional or class-based.
a. Functional Components
Functional components are simple JavaScript functions that return JSX. They are easier to read, test, and maintain.
-
Basic Functional Component:
import React from 'react'; function Greeting(props) { return <h1>Hello, {props.name}!</h1>; } export default Greeting;
-
Using Arrow Functions:
const Greeting = (props) => { return <h1>Hello, {props.name}!</h1>; };
b. Class Components
Class components are ES6 classes that extend React.Component
. They can manage their own state and have access to lifecycle methods.
-
Basic Class Component:
import React, { Component } from 'react'; class Greeting extends Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } export default Greeting;
-
State in Class Components:
class Counter extends Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } }
3. Props (Properties)
Props are read-only inputs passed from parent to child components. They allow components to receive data and behave dynamically.
-
Passing Props:
function App() { return <Greeting name="Alice" />; }
-
Accessing Props in Functional Components:
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; }
-
Accessing Props in Class Components:
class Greeting extends Component { render() { return <h1>Hello, {this.props.name}!</h1>; } }
4. State
State is a dynamic data structure that allows components to manage and respond to changes over time. Unlike props, state is managed within the component.
a. Using useState
Hook in Functional Components
The useState
Hook lets you add state to functional components.
- Example:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Counter;
b. State in Class Components
State is initialized in the constructor and updated using setState
.
- Example:
class Counter extends Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } }
5. Event Handling
React handles events using camelCase syntax and passes event handlers as functions.
- Example:
function Button() { const handleClick = () => { alert('Button clicked!'); }; return <button onClick={handleClick}>Click Me</button>; }
6. Conditional Rendering
Conditional rendering allows you to render different UI elements based on certain conditions using JavaScript operators like if
, &&
, and ternary ? :
.
-
Using If-Else:
function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return <h1>Welcome back!</h1>; } return <h1>Please sign in.</h1>; }
-
Using Ternary Operator:
function Greeting(props) { return ( <div> {props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>} </div> ); }
-
Using Logical AND Operator:
function Notification(props) { return ( <div> {props.message && <p>{props.message}</p>} </div> ); }
7. Lists and Keys
Rendering lists of elements requires using the map
function and assigning a unique key
to each item to help React identify which items have changed.
- Example:
function TodoList(props) { return ( <ul> {props.todos.map((todo) => ( <li key={todo.id}>{todo.text}</li> ))} </ul> ); }
8. Styling
React offers various ways to style components, including plain CSS, CSS Modules, inline styles, and CSS-in-JS libraries like Styled Components.
-
Using Inline Styles:
function StyledButton() { const buttonStyle = { backgroundColor: 'blue', color: 'white', padding: '10px 20px', border: 'none', borderRadius: '5px', }; return <button style={buttonStyle}>Click Me</button>; }
-
Using CSS Classes:
// App.css .button { background-color: blue; color: white; padding: 10px 20px; border: none; border-radius: 5px; } // Component.js import './App.css'; function StyledButton() { return <button className="button">Click Me</button>; }
9. Hooks
Hooks are functions that let you use state and other React features in functional components.
a. useEffect Hook
The useEffect
Hook lets you perform side effects in functional components, such as data fetching or manual DOM manipulation.
- Example:
import React, { useState, useEffect } from 'react'; function DataFetcher() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then((response) => response.json()) .then((json) => setData(json)) .catch((error) => console.error('Error fetching data:', error)); }, []); // Empty dependency array means this runs once after initial render if (!data) { return <p>Loading...</p>; } return ( <div> <h1>Fetched Data:</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); } export default DataFetcher;
b. Custom Hooks
Custom Hooks allow you to extract and reuse stateful logic across multiple components.
-
Example:
import { useState, useEffect } from 'react'; function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { fetch(url) .then((response) => response.json()) .then((json) => { setData(json); setLoading(false); }) .catch((error) => { console.error('Error fetching data:', error); setLoading(false); }); }, [url]); return { data, loading }; } export default useFetch;
-
Using Custom Hook:
import React from 'react'; import useFetch from './useFetch'; function UserProfile() { const { data, loading } = useFetch('https://api.example.com/user'); if (loading) { return <p>Loading...</p>; } return ( <div> <h1>{data.name}</h1> <p>Email: {data.email}</p> </div> ); } export default UserProfile;
10. Routing with React Router
While not part of React’s core library, React Router is the standard library for handling routing in React applications, enabling navigation without full page reloads.
- Basic Setup:
import React from 'react'; import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'; function Home() { return <h2>Home</h2>; } function About() { return <h2>About</h2>; } function App() { return ( <Router> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Switch> </Router> ); } export default App;
11. Forms in React
Handling forms involves managing form data through state, using controlled components where form elements derive their values from state and update state on changes.
- Example:
import React, { useState } from 'react'; function NameForm() { const [name, setName] = useState(''); const handleSubmit = (e) => { e.preventDefault(); alert(`Hello, ${name}!`); }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> </label> <button type="submit">Submit</button> </form> ); } export default NameForm;
12. State Lifting
When multiple components need to share the same state, the state is "lifted" up to their closest common ancestor. This ensures a single source of truth and consistent data flow.
- Example:
import React, { useState } from 'react'; function Parent() { const [value, setValue] = useState(''); return ( <div> <ChildA value={value} setValue={setValue} /> <ChildB value={value} /> </div> ); } function ChildA({ value, setValue }) { return <input value={value} onChange={(e) => setValue(e.target.value)} />; } function ChildB({ value }) { return <p>Value: {value}</p>; } export default Parent;
13. React Developer Tools
React provides browser extensions like React Developer Tools for Chrome and Firefox. These tools help in inspecting the component hierarchy, state, and props in real-time, facilitating easier debugging and development.
14. Best Practices
- Keep Components Small and Focused: Each component should ideally handle a single piece of functionality.
- Use Descriptive Naming: Name components and variables clearly to reflect their purpose.
- Avoid State Mutations: Always update state immutably to prevent unexpected behavior.
- Optimize Performance: Use memoization techniques (
React.memo
,useMemo
,useCallback
) to prevent unnecessary re-renders. - Organize File Structure: Maintain a logical and consistent file structure for components, styles, and assets.
Conclusion
ReactJS syntax revolves around building reusable components using JSX, managing state with Hooks or class-based state, handling events, and efficiently rendering dynamic UIs with the Virtual DOM. Mastering these fundamental concepts and their syntax is essential for developing robust and scalable React applications. By practicing component creation, state management, event handling, and integrating with related libraries like React Router, you can build comprehensive and interactive user interfaces with React.
GET YOUR FREE
Coding Questions Catalog