Day 9: Environment Variables and Toastify in React

What are Environment Variables?

Environment variables in React serve as dynamic configurations for our application. They act like adjustable parameters that influence the way our program without requiring code changes.

Imagine your React application as a complex structure, like a castle, constructed from various components. Each environment variable serves as a building block, providing crucial information to different parts of your application. For instance, they might dictate where to locate essential resources like images or how to interact with external services such as APIs.

By leveraging environment variables, developers can easily fine-tune their applications' behaviour without delving into extensive code modifications.

How to use environment variables?

Setting Up Environment Variables

Developers define these variables outside of the code, usually in a file named .env. Each variable has a name and a value, like

REACT_APP_API_KEY=API_KEY

This file is not committed to the code repository to keep sensitive information safe.

Accessing Environment Variables

Inside the React code, we can access these environment variables using process.env.VARIABLE_NAME, where VARIABLE_NAME is the name of the variable we define. For example, if you have an environment variable named REACT_APP_API_KEY, we can access its value like process.env.REACT_APP_API_KEY.

Using Environment Variables

Once you've accessed an environment variable, you can use its value wherever needed in your React application. For instance, if your variable stores an API key, you can use it to make API requests.

const EnvComponent = () => {
  // Accessing environment variable
  const apiKey = process.env.REACT_APP_API_KEY

  // Using the environment variable
  const fetchData = async () => {
    try {
      const response = await fetch(`https://api.example.com/data?key=${apiKey}`)
      const data = await response.json()
      console.log(data)
    } catch (error) {
      console.error('Error fetching data:', error)
    }
  }
  return (
    <div>
      <button onClick={fetchData}>Fetch Data</button>
    </div>
  )
}
export default EnvComponent        

What are "Toasts"?

Toastify is a handy tool used by developers to display brief messages, called "toasts," to users. These toasts are like gentle reminders or notifications, providing users with helpful information without being intrusive. They appear briefly, convey the message, and then gracefully disappear, allowing users to continue their interactions with the app seamlessly. It's a polished way to enhance the user experience without overwhelming them with unnecessary noise.

Using a "Toast"

Using toast notifications in React involves using a library like 'react-toastify', which provides components and utilities for displaying these notifications.

Firstly, we need to install react-toastify and its dependencies.

npm install react-toastify        

Next, in the component where we want to use toast notifications, we import the ToastContainer component from react-toastify.

import { ToastContainer } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'        

To render the Toast component, we place the ToastContainer component at the top level of application, typically within root component or main layout component.

function App() {
  return (
    <div>
      <ToastContainer />
    </div>
  )
}        

Now, whenever we want to show or trigger a toast notification, we can use the toast function provided by react-toastify.

import { toast } from 'react-toastify'
const ToastComponent = () => {
toast.success('Product Saved!')
}
const Display = () => {
  return (
    <button onClick={ToastComponent}>Show Toast</button>
  )
}        

Thank you for your insightful lecture, Bikash Karki .

要查看或添加评论,请登录

Aastha Sharma的更多文章

  • ExpressJS

    ExpressJS

    What is ExpressJS? Express.js is a Node.

  • Day 13: Forms in React (Formik and Yup)

    Day 13: Forms in React (Formik and Yup)

    On the thirteenth day, I learned about forms in React, the Fragment tag, and react-icons in the react application…

  • Day 12: localStorage

    Day 12: localStorage

    It can be infuriating to close a webpage while filling out a form accidentally. We lose all the data already filled and…

  • Day 11: Layout, Offset, and the useParams Hook

    Day 11: Layout, Offset, and the useParams Hook

    Layout and Offset In React, "offset" and "limit" are commonly used when dealing with paginated data. These terms are…

  • Day 10: Using API data and Pagination in React

    Day 10: Using API data and Pagination in React

    APIs in React APIs (Application Programming Interfaces), in React, are used to fetch data from external sources, such…

  • Day 8:React Hooks (Part 2)

    Day 8:React Hooks (Part 2)

    After a thorough introduction to React Hooks and the useState hook on day 7, we learned about the useEffect hook in…

  • Day 7: React Hooks

    Day 7: React Hooks

    On the seventh day of learning React, we learned about React hooks, their use, and their applications. React Components…

  • Day 6: Dynamic React Components using Props

    Day 6: Dynamic React Components using Props

    React utilizes a component-based architecture that enables developers to create reusable and modular UI elements. A…

  • Day 5: React Layouts, Outlets, and Links

    Day 5: React Layouts, Outlets, and Links

    On the fifth day of learning react, we grabbed on concepts like layouts, outlets, and links in React. They are…

  • Day 4: React-Router-DOM and BootStrap

    Day 4: React-Router-DOM and BootStrap

    On the fourth day of learning React, we learned about installing Bootstrap and React router DOM, all thanks to our…

社区洞察

其他会员也浏览了