Function Component Base
A function component is a building block in React that defines a portion of a web app's UI. It's a JavaScript function that returns JSX elements to render.Example
function MyComponent() {
return <h1>Hello world!</h1>;
}
Importing React
Importing the React library is essential to use its features. It creates an object containing JSX and component creation capabilities.Example
import React from 'react';
JSX Capitalization
Capitalization in JSX distinguishes between HTML tags and component instances. Components start with uppercase letters, while HTML tags are lowercase. This helps React differentiate between them during rendering.Example
// Component instance
<MyComponent />
// HTML tag
<div>
Object Properties as Attribute Values
You can set JSX attribute values using JavaScript objects, adding flexibility to component creation.Example
const seaAnemones = {
src: '...',
alt: 'Sea Anemones',
width: '300px',
};
function SeaAnemones() {
return (
<div>
<img src={seaAnemones.src} alt={seaAnemones.alt} width={seaAnemones.width} />
</div>
);
}
Return Statement
The `return` statement in a function component defines what the component will render.Example
function ReturnComponent() {
return <div>This is returned by the component.</div>;
}
Logic Before Return
JavaScript logic can be included before the `return` statement in a component.Example
function LogicBeforeReturn() {
const value = 42;
const doubledValue = value * 2;
return <p>Value: {doubledValue}</p>;
}
Rendering a Component
Components are rendered within a root container. In this example, the `MyComponent` component is rendered into an element with the ID of "app".Example
ReactDOM.createRoot(document.getElementById('app')).render(<MyComponent />);
Multi-line JSX Expressions
Parentheses are used for multi-line JSX expressions.Example
return (
<blockquote>
<p>Quote content.</p>
<cite>Author</cite>
</blockquote>
);
Importing and Exporting Components in React
Components can be exported and imported to create modular and reusable code.Example
// Greeting.js
function Greeting() {
return <h1>Hello!</h1>;
}
export default Greeting;
// App.js
import Greeting from './Greeting'
React Components
Components are the core of a React app. They define reusable pieces of UI, enhancing code organization and reusability.Example
function MyFunctionComponent() {
return <h1>Hello from function component!</h1>;
}
class MyClassComponent extends React.Component {
render() {
return <h1>Hello from class component!</h1>;
}
}
Returning HTML Elements and Components
In the latest version of React, you can return both HTML elements and custom components from a functional component's JSX. This allows you to create complex UI structures by composing smaller components together.Example
import React from 'react';
function App() {
return (
<div>
<h1>Hello, React!</h1>
<p>This is an example of returning HTML elements.</p>
<CustomComponent />
</div>
);
}
function CustomComponent() {
return <p>This is a custom component.</p>;
}
export default App;
Accessing Props
Props (short for properties) are a way to pass data from a parent component to a child component in React. In the latest React version, you can access props easily within a functional component.Example
import React from 'react';
function Greeting(props) {
return <p>Hello, {props.name}!</p>;
}
function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}
export default App;
defaultProps and props
defaultProps is a feature in React that allows you to set default values for props in a component. These default values are used if the parent component doesn't provide the prop explicitly.Example
import React from 'react';
function Greeting(props) {
return <p>Hello, {props.name}!</p>;
}
Greeting.defaultProps = {
name: 'Guest', // Default value for the name prop
};
function App() {
return (
<div>
<Greeting /> {/* Will use the default name */}
<Greeting name="Alice" /> {/* Will override the default name */}
</div>
);
}
export default App;
props.children
props.children is a special prop in React that allows you to pass child elements to a component. This is particularly useful for creating reusable components that wrap around other content.Example
import React from 'react';
function Card(props) {
return (
<div className="card">
{props.children}
</div>
);
}
function App() {
return (
<Card>
<h2>Welcome to my website</h2>
<p>This is some content inside the card.</p>
</Card>
);
}
export default App;
Binding this keyword
In React, class methods need to be properly bound to the component's instance to access ‘this’. This ensures that ‘this’ inside the method refers to the correct instance of the component.Example
class MyComponent extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// Access and modify component state here
}
render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
Call super() in the Constructor
When extending a React class component, the ‘super()’ call in the constructor initializes the parent class (React.Component) and allows you to set up the initial state and bind methods correctly.Example
class MyComponent extends React.Component {
constructor() {
super();
this.state = {
count: 0
};
}
// Other methods and render() go here
}
Component State in Constructor
Initializing the component state in the constructor is a common practice. It's used to set up the initial state of the component.Example
class Counter extends React.Component {
constructor() {
super();
this.state = {
count: 0
};
}
// Other methods and render() go here
}
this.setState()
The ‘setState()’ method is used to update the component's state. It's the recommended way to modify state, as React ensures the component re-renders appropriately.Example
class Counter extends React.Component {
constructor() {
super();
this.state = {
count: 0
};
}
incrementCount() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.incrementCount()}>Increment</button>
</div>
);
}
}
Dynamic Data in Components
React components can display dynamic data using curly braces ‘{}’ within JSX. You can insert variables, expressions, or values from state.Example
class DynamicDataComponent extends React.Component {
render() {
const dynamicText = "Hello, Dynamic World!";
return <p>{dynamicText}</p>;
}
}
Don’t Change State While Rendering
Modifying the state directly during the rendering phase can lead to unexpected behavior. Always use ‘setState()’ to update state and trigger re-renders properly.Example
// Bad practice
render() {
this.state.count = 5; // Avoid modifying state directly
return <p>{this.state.count}</p>;
}
// Good practice
render() {
return <p>{this.state.count}</p>;
}