Article by: venomity.near
Bridging web development with blockchain innovation, this guide delves into employing React for crafting dynamic user interfaces on NEAR Protocol. Tailored for developers at any level, it highlights React‘s component-based architecture alongside the decentralization capabilities of NEAR. Through practical JSX examples and UI/UX best practices, it serves as a comprehensive resource for leveraging React in the NEAR ecosystem, paving the way for efficient, maintainable DApp development.
Component Architecture
Designing React components for NEAR Protocol involves understanding the basics of React and JSX. React’s component architecture allows developers to build encapsulated components that manage their own state, leading to efficient and maintainable code.
Create a Simple JSX Element
Before we dive into creating a simple JSX element, it’s essential to ensure you’re familiar with the foundational concepts of React. If you’ve found this guide first and feel you might be missing some context, check out BOS Guide #1: Introduction to React & BOS. JSX is a syntax extension for JavaScript used in React to describe the UI. A simple JSX element can be created as follows:
const element = <h1>Hello, world!</h1>; |
This code snippet creates a basic element using JSX, which is similar to HTML but with the power of JavaScript.
Image code here.
Create a Complex JSX Element
Complex JSX elements can be composed of multiple elements. For example:
const complexElement = ( <div> <h1>Heading</h1> <p>Paragraph</p> </div> ); |
This creates a div element containing an h1 and a p element, demonstrating how JSX can nest multiple elements.
Image code here.
Add Comments in JSX
Adding comments in JSX is slightly different from regular JavaScript:
const elementWithComment = ( <div> {/* This is a comment in JSX */} <h1>Hello, world!</h1> </div> ); |
The curly braces {} are used to embed a JavaScript expression, including comments.
Image code here.
Define an HTML Class in JSX
In JSX, the class attribute is written as className due to class being a reserved word in JavaScript:
const elementWithClass = <div className=“container”>Content</div>; |
Image code here.
Learn About Self-Closing JSX Tags
JSX follows XML rules, so every tag must be closed. Tags without children can be self-closed:
const selfClosingTag = <img src=“image.jpg” alt=“Description” />; |
Image code here.
Create a Stateless Functional Component
Stateless functional components offer a streamlined method for crafting parts of your UI in React. These components, as the name suggests, are functions that return UI elements but do not hold or manage state. Their simplicity and focus on presentation make them ideal for many scenarios in React development, especially when the goal is to render UI based on props passed down from parent components.
Consider the ‘Welcome’ component, a prime example of a stateless functional component. It takes ‘props’ as an argument and uses them to dynamically render UI:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } |
Image code here.
In this snippet, ‘props’ is an object containing properties passed to the component. The ‘Welcome’ component accesses the ‘name’ property from ‘props’ to display a personalized greeting. This approach demonstrates the power of props in React, allowing components to render dynamic content based on external data.
Create a Component with Composition
Components can be composed together:
function App() { return ( <div> <Welcome name=“Alice” /> <Welcome name=“Bob” /> </div> ); } |
Image code here.
Use React to Render Nested Components
React allows for nesting components within other components:
function App() { return ( <div> <Header /> <MainContent /> <Footer /> </div> ); } |
Image code here.
Compose React Components
Composition in React is a powerful concept that allows developers to build complex user interfaces (UIs) by piecing together smaller, reusable components. This approach is akin to using building blocks or puzzle pieces to create a larger picture. It’s a fundamental principle in React and a common practice in modern web development.
Imagine you’re building a LEGO model. You have different LEGO pieces, each with its own shape and colour. Individually, these pieces aren’t much to look at, but when you put them together in a certain way, you can create a complex and beautiful model.
In React, components are like these LEGO pieces. A component is a small, reusable piece of your UI. It could be a button, a header, a form, or any other part of a webpage. Just like LEGO pieces, these components can be used and combined in various ways to build a more complex UI.
UI/UX Best Practices
When designing React components, it’s important to follow UI/UX best practices to ensure a good user experience.
Introducing Inline Styles
Inline styles can be added directly to JSX elements using a JavaScript object:
const style = { fontSize: ’14px’ }; const element = <div style={style}>Text</div>; |
Image code here.
Add Inline Styles in React
Inline styles in React are specified as objects:
const element = <div style={{ color: ‘blue’ }}>Blue Text</div>; |
Image code here.
Use Advanced JavaScript in the React Render Method
React’s render method can use advanced JavaScript, like map or filter, to dynamically create elements.
Using map in React’s Render Method
What is map?: map is a JavaScript array method that transforms each element in an array and returns a new array with the transformed elements. It’s commonly used to iterate over a list of items and generate a React element for each one.
How is map used in React? In React, map is often used to convert an array of data into an array of JSX elements. For example, if you have an array of objects representing tasks, you can use map to create a list item (<li>) for each task.
Using filter in React’s Render Method
What is filter? filter is another JavaScript array method that creates a new array with only those elements that pass a test implemented by a provided function.
How is filter used in React? In React, filter can be used to conditionally include elements in the rendering process. For example, you might have a list of items, but you only want to render those that meet certain criteria.
Render with an If-Else Condition
Conditional rendering can be achieved using if-else statements:
function Welcome(props) { if (props.isLoggedIn) { return <UserGreeting />; } return <GuestGreeting />; } |
Image code here.
Image code here.
Use && for a More Concise Conditional
The && operator can be used for a more concise conditional rendering:
function Mailbox(props) { return ( <div> <h1>Hello!</h1> {props.unreadMessages.length > 0 && <h2> You have {props.unreadMessages.length} unread messages. </h2> } </div> ); } |
Image code here.
Use a Ternary Expression for Conditional Rendering
Ternary expressions offer a concise way to handle conditional rendering:
const element = ( <div> {isLoggedIn ? <LogoutButton /> : <LoginButton />} </div> ); |
Image code here.
Image code here.
Render Conditionally from Props
Props (properties) can be used to conditionally render components:
function Welcome(props) { return <div>{props.isLoggedIn ? <UserGreeting /> : <GuestGreeting />}</div>; } |
Image code here.
Image code here.
Change Inline CSS Conditionally Based on Component State
Inline CSS can be changed based on the component’s state:
function WarningBanner(props) { const style = { color: props.warn ? ‘red’ : ‘black’ }; return <div style={style}>Warning!</div>; } |
Image code here.
Try It Yourself: Design Your Own Component
Designing React components for the NEAR Protocol involves understanding JSX basics which is just this article, component architecture, state management, and UI/UX best practices. By leveraging these concepts, developers can create efficient, maintainable, and user-friendly applications on the NEAR blockchain platform.
Now that you’ve learned the basics, it’s time to put your knowledge into practice. We challenge you to create a custom component that could be used. Here is an idea to get you started:
- A user profile card displaying NEAR wallet information
Share Your Work and Collaborate
We’ve set up a dedicated forum thread where you can share your components, ask questions, and help others with their projects. Visit Discussion to post your work and engage with the community.
Don’t forget to check out the BAC.inc bugs thread here to report any issues you encounter or offer solutions to existing bugs. Your contributions are invaluable to improving the NEAR development experience for everyone.
Feedback and Further Learning
We encourage you to review and comment on the work of your peers. Sharing insights and solutions can lead to better understanding and innovation. If you have any questions or need assistance, don’t hesitate to ask in the forum. Let’s learn and grow together as a community!
This article was crafted in collaboration with Browns Avenue Consulting Inc. (BAC Inc.), as part of our initiative to simplify the development process for blockchain applications, thereby fostering innovation and growth. This effort underscores our dedication to providing comprehensive resources and support to developers navigating NEAR protocol. To learn more about the initiatives supported by the Marma J Foundation and how BAC Inc. contributes to the development and education within the blockchain community, please visit the BAC Inc. DAO or join BAC Inc.’s Telegram channel for updates and discussions.