<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: CheriseFoster</title>
    <description>The latest articles on DEV Community by CheriseFoster (@cherisefoster).</description>
    <link>https://dev.to/cherisefoster</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1032061%2Ff9c2ad66-d39f-46f0-9f1f-3436976746ac.jpg</url>
      <title>DEV Community: CheriseFoster</title>
      <link>https://dev.to/cherisefoster</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/cherisefoster"/>
    <language>en</language>
    <item>
      <title>Mastering Asynchronous Actions in Redux with createAsyncThunk</title>
      <dc:creator>CheriseFoster</dc:creator>
      <pubDate>Fri, 15 Dec 2023 00:15:51 +0000</pubDate>
      <link>https://dev.to/cherisefoster/mastering-asynchronous-actions-in-redux-with-createasyncthunk-57bc</link>
      <guid>https://dev.to/cherisefoster/mastering-asynchronous-actions-in-redux-with-createasyncthunk-57bc</guid>
      <description>&lt;p&gt;In my previous blog post, I talked about Redux and broke down creating a slice to manage state in your applications. In this blog post, we are going to talk about another important tool in the Redux Toolkit called 'createAsyncThunk.' &lt;/p&gt;




&lt;h2&gt;
  
  
  What is 'createAsyncThunk'?
&lt;/h2&gt;

&lt;p&gt;Other than being an obnoxious term to say and type, createAsyncThunk is a function from Redux's Toolkit to help manage asynchronous actions and data fetching. It's another tool to help reduce boilerplate code by generating action types for each stage of the async request (pending, fulfilled, rejected).&lt;/p&gt;




&lt;p&gt;To implement createAsyncThunk into your slice, start by importing it the same way you import createSlice from the Redux Toolkit. The code below is an example from a project of mine where I created a houseSlice (each house has an address and information about the residents). Instead of fetching the data in my React component, it's in the slice:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

export const fetchHouses = createAsyncThunk('houses/fetchHouses', async () =&amp;gt; {
    const response = await fetch('/api/houses');
    const data = await response.json();
    return data;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Breaking this down, we are exporting and defining our thunk for the house data. &lt;code&gt;houses/fetchHouses&lt;/code&gt; is an action type string that uniquely identifies a specific action to be dispatched. Next, we define the logic for the async operation. Setting the response as a  variable, this is where we include the fetch for the data. Similarly, we parse the JSON response body and return the data, which then becomes the "fulfilled" action payload.&lt;/p&gt;

&lt;p&gt;If we were going to fetch the data in our component, it would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Houses() {
  //add state
  const [houses, setHouses] = useState([]);

  useEffect(() =&amp;gt; {
    fetch('/api/houses')
    .then(res) =&amp;gt; res.json())
    .then((data) =&amp;gt; {
     setHouses(data)
   });
  }, [])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a really simple fetch request, however, when you have other things you need to add in, like maybe a request to handle errors, it can take up a lot of space in your component. &lt;/p&gt;

&lt;p&gt;Let's add reducers to our slice, but utilizing extraReducers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const housesSlice = createSlice({
    name: 'houses',
    initialState: [],
    reducers: {},
    extraReducers: {
        [fetchHouses.pending]: (state) =&amp;gt; {
            state.loading = true;
            state.error = null;
        },
        [fetchHouses.fulfilled]: (state, action) =&amp;gt; {
            return action.payload;
        },
       [fetchHouses.rejected]: (state, action) =&amp;gt; {
            state.loading = false; 
            state.error = action.error.message;
        },
    }
});

export default housesSlice.reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  extraReducers, why?
&lt;/h2&gt;

&lt;p&gt;If you read my previous blog post, this code will look familiar to you. Quick run through of the first 3 lines: defining the slice, naming the slice, and setting the initial state of the slice. Normally, your reducers would go in the reducer object, and each reducer you want to use would need to be exported to be used in the components. Here, we are setting our reducers as an empty object and handling actions via extraReducers. ExtraReducers allow the handling of actions defined outside of the slice. It's useful for handling async operations like the actions created by createAsyncThunk, which are handled outside of the slice but need to be handled by the slice reducer.&lt;/p&gt;

&lt;p&gt;If that doesn't make any sense, don't worry, you're not alone. There's a learning curve with Redux and it takes some time to get used to and understand.&lt;/p&gt;

&lt;p&gt;The best description I've read to explain the difference between reducers and extraReducers is from a stack overflow question. Here's the answer: &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The reducers property both creates an action creator function and responds to that action in the slice reducer. The extraReducers allows you to respond to an action in your slice reducer but does not create an action creator function.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Side note: "pending," "fulfilled," and "rejected" are action types that are built into the createAsyncThunk API, so use those action words and don't change them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Code explained
&lt;/h2&gt;

&lt;p&gt;In the extraReducers, we are handling the pending state of fetchHouses. The state loading is true because, well, it's loading. And state errors are null because the promise isn't fulfilled or rejected yet:&lt;br&gt;
&lt;code&gt;[fetchHouses.pending]: (state) =&amp;gt; {&lt;br&gt;
            state.loading = true;&lt;br&gt;
            state.error = null;&lt;br&gt;
        },&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Next, we are handling the fulfilled state of fetchHouses by updating the state with the fetched data and setting loading to false since the request is complete:&lt;br&gt;
&lt;code&gt;[fetchHouses.fulfilled]: (state, action) =&amp;gt; {&lt;br&gt;
            state.data = action.payload; &lt;br&gt;
            state.loading = false;&lt;br&gt;
        },&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Last, we are handling the rejected state of fetchHouses by setting loading to false and updating the state with an error message:&lt;br&gt;
&lt;code&gt;[fetchHouses.rejected]: (state, action) =&amp;gt; {&lt;br&gt;
            state.loading = false; &lt;br&gt;
            state.error = action.error.message; &lt;br&gt;
        },&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Back in the React component
&lt;/h2&gt;

&lt;p&gt;Now that our slice is done, it's time to add it into our component. This step is so simple you're going to think something is missing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { fetchHouses } from '../redux/housesSlice';

function HouseContainer() {
    const dispatch = useDispatch();

    useEffect(() =&amp;gt; {
        dispatch(fetchHouses());
    }, [dispatch]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it! When &lt;code&gt;dispatch(fetchHouses())&lt;/code&gt; is called, it initiates the asynchronous operations defined in the fetchHouses thunk. So if  the operation is a success, fetchHouses.fulfilled is dispatched, and same with if it's rejected. &lt;/p&gt;

&lt;p&gt;If you wanted to access each state, you could by using useSelector. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function HouseContainer() {
    const loading = useSelector((state) =&amp;gt; state.houses.loading);
    const error = useSelector((state) =&amp;gt; state.houses.error);

    if (loading) return &amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;;
    if (error) return &amp;lt;div&amp;gt;Error: {error}&amp;lt;/div&amp;gt;;

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Using createAsyncThunk from Redux is a streamlined and more efficient way to handle asynchronous logic in your Redux applications. It can significantly reduce boilerplate code in your components, and provides a clear structure for async actions. Overall, it's cleaner and more maintainable.&lt;/p&gt;

&lt;p&gt;Check out the Redux Toolkit docs at &lt;a href="https://redux-toolkit.js.org/"&gt;DOCS&lt;/a&gt;&lt;/p&gt;

</description>
      <category>redux</category>
      <category>react</category>
      <category>coding</category>
      <category>javascriptlibraries</category>
    </item>
    <item>
      <title>Using Redux Toolkit for State Management in React</title>
      <dc:creator>CheriseFoster</dc:creator>
      <pubDate>Wed, 08 Nov 2023 21:22:51 +0000</pubDate>
      <link>https://dev.to/cherisefoster/using-redux-toolkit-for-state-management-in-react-2nmm</link>
      <guid>https://dev.to/cherisefoster/using-redux-toolkit-for-state-management-in-react-2nmm</guid>
      <description>&lt;p&gt;If you're building a large and complex application, it's no question that trying to manage state can get tricky and redundant. Insert: Redux. Redux acts as a state container for JavaScript applications so that state can be managed in separate files and accessed in your React components. However, Redux can be complicated, which is why Redux Toolkit was introduced to make managing state easier and simpler, reducing boilerplate code and hiding the difficult parts of Redux to ensure a good developer experience. If you've never used Redux before, there is a learning curve, but this blog is here to break down the basics. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But first, why would I use Redux?&lt;/strong&gt;&lt;br&gt;
A few reasons to use Redux would include: if you have large amounts of state in your application that are needed in various places, if your state is updated frequently over time, or if your application has a medium to large-sized codebase and might be worked on by many people.&lt;/p&gt;



&lt;h2&gt;Core Concepts&lt;/h2&gt;

&lt;p&gt;There are 3 core concepts in Redux:&lt;/p&gt;

&lt;p&gt;-&lt;strong&gt;Store&lt;/strong&gt;: This is what holds the state of your application. It allows access to state via getState(),and allows state to be updated via dispatch(action).&lt;br&gt;
-&lt;strong&gt;Action&lt;/strong&gt;: Actions describe what happened. They are the only way your app can interact with the store. Actions must have a "type" property that describes something that happened in the app.&lt;br&gt;
-&lt;strong&gt;Reducers&lt;/strong&gt;: Reducers tie the store and actions together by specifying how the app's state changes in response to actions sent to the store. In simpler terms, it handles the action and describes how to update state.&lt;/p&gt;



&lt;h2&gt;Redux Principles&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;The global state of your application is stored as an object inside a single store. You can maintain your application state in a single object to be managed by the Redux &lt;em&gt;store&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;To update the state of your application, you need to let Redux know about that with an &lt;em&gt;action&lt;/em&gt;. The state object is not allowed to be updated directly, meaning it is immutable. But don't worry, Redux handles this for you by making a copy of the current state.&lt;/li&gt;
&lt;li&gt;To specify how the state tree is updated based on actions, you write pure &lt;em&gt;reducers&lt;/em&gt; (i.e. functions). Reducers take the previous state coupled with an action and return the next state.
&lt;strong&gt;reducer = (previousState, action) =&amp;gt; newState&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;Let's Get Coding&lt;h2&gt;

&lt;/h2&gt;
&lt;/h2&gt;
&lt;p&gt;To get started, make sure you have redux toolkit installed:&lt;br&gt;
&lt;code&gt;npm install @reduxjs/toolkit react-redux&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;I created an application with a sign up/log in feature. In my src folder lies my components folder with all of my React components, and another folder I named redux. Each file under the redux folder contains state for various parts of my application. The first file to create in your redux folder should be the store.js file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//store.js

import { configureStore } from "@reduxjs/toolkit";

export default configureStore({
    reducer: {

    }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;configureStore&lt;/code&gt; import creates the Redux store from Toolkit and is a way to pass in all of our reducers. When we make a Redux "slice", which is your reducer logic and actions for a single feature in your app (or your state for a particular feature), we will pass that into the store reducer.&lt;/p&gt;

&lt;p&gt;To keep things simple and organized, I like to put the word "slice" into each of my slice file names. I created my authentication file under my redux folder and named it authSlice.js. &lt;/p&gt;

&lt;p&gt;In authSlice.js:&lt;/p&gt;

&lt;p&gt;Import &lt;code&gt;createSlice&lt;/code&gt; from the Redux Toolkit library, this allows us to write our logic easier and with less boilerplate:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//authSlice.js

import { createSlice } from '@reduxjs/toolkit'

const authSlice = createSlice({
  name: 'auth',
  initialState: {
    user: null,
    isAuthenticated: false,
    isLoading: false,
    error: null,
  },
  reducers: {

  }
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;const authSlice = createSlice({...})&lt;/code&gt; creates a single slice of the Redux state.&lt;br&gt;
In the next line, "name: 'auth'", we give a name to the slice which is referenced back in the store.js file as "auth: authReducer." The name can be whatever you want but keep it simple and easy.&lt;/p&gt;

&lt;p&gt;We need to define an initial state for the slice, similar to defining your initial state when using state in a React component. If I were to just use  state inside my component instead of Redux, it might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function AuthenticationComponent() {
  const [user, setUser] = useState(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, there is much less code using Redux! Let's move on to the reducer object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//authSlice.js

reducers: {
    loginStart: (state) =&amp;gt; {
      state.isLoading = true;
    },
    loginSuccess: (state, action) =&amp;gt; {
      state.isLoading = false;
      state.isAuthenticated = true;
      state.user = action.payload;
      state.error = null;
    },
    loginFailure: (state, action) =&amp;gt; {
      state.isLoading = false;
      state.error = action.payload;
    },
    logout: (state) =&amp;gt; {
      state.isAuthenticated = false;
      state.user = null;
    },
  },
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's common practice in Redux to use Start (or often "Begin"), Success, and Failure (and sometimes Update) in the reducer object. It's not necessary, but it helps to handle the different states of async request within a reducer.&lt;/p&gt;

&lt;h4&gt;Actions and Payload&lt;/h4&gt;

&lt;p&gt;An action is a plain JS object that has a 'type' property which indicates the action that's being performed (logging in) and usually a 'payload' field which contains any data that should be used to update the state. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;'loginStart': Takes the current state and marks the start of the login process by setting the state.isLoading to true.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;'loginSuccess': Takes the current state and an action. It sets isLoading to false as the login attempt has finished, updates isAuthenticated to true indicating a successful login, sets user to the payload containing user data, and clears any errors by setting error to null.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;'loginFailure': Sets isLoading to false since the login attempt has concluded, but an error occurred, and then sets error to the payload, which should contain information about what went wrong.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;'logout': Sets isAuthenticated to false and logging the user out, and resets the user to null, clearing any stored user information.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The logout action doesn't require a payload since there's no need for additional data to perform these operations. The type of the action (which, thanks to Redux Toolkit, is automatically generated) is all the reducer needs to update the state accordingly.&lt;/p&gt;

&lt;p&gt;Finally, we need to be able to use this code in other files, so we need to export it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//authSlice.js

export const { 
  loginStart, 
  loginSuccess, 
  loginFailure, 
  logout,
} = authSlice.actions;
export default authSlice.reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The export const {...} line includes all of our functions that return action objects when called. The reducer function authSlice.reducer is exported as the default export of the module. This reducer is what we would include in our store (store.js) configuration to handle state transitions based on the actions dispatched. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Make sure you import the reducer slice in your store.js file after you create it!&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//store.js

import { configureStore } from "@reduxjs/toolkit";
import authReducer from './authSlice';

export default configureStore({
    reducer: {
        auth: authReducer
    }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You need a way to provide the Redux store to all of the components in your application that need to access the state or actions. To do this, use the "Provider" component from the react-redux library. "Provider" is a higher-order component that takes your Redux store as a prop and allows the rest of you application access to it.&lt;/p&gt;

&lt;p&gt;In your index.js file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//index.js

import App from "./components/App";
import store from "./redux/store";
import { Provider } from "react-redux";

const container = document.getElementById("root");
const root = createRoot(container);
root.render(
    &amp;lt;Router&amp;gt;
      &amp;lt;Provider store={store}&amp;gt;
        &amp;lt;App /&amp;gt;
      &amp;lt;/Provider&amp;gt;
    &amp;lt;/Router&amp;gt;
  );

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can now successfully deploy your Redux state into whatever components of your application you need. In my Authentication component, I deployed the loginStart, loginSuccess, and loginFailure functions. Import the useDispatch hook provided by the react-redux library so you can dispatch actions to the store from within your React components:&lt;/p&gt;

&lt;p&gt;I used formik in this component to handle the sign in form:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//AuthenticationForm Component

import { useDispatch, useSelector } from 'react-redux';
import { loginStart, loginSuccess, loginFailure } from "../redux/authSlice";

function AuthenticationForm() {
    const dispatch = useDispatch();

const signInFormik = useFormik({
        {code}...
        },
        validationSchema: signInSchema,
        onSubmit: (values, { ... }) =&amp;gt; {
            dispatch(loginStart()); // Dispatch start action
            fetch('/api/login', {
                {code}...,
            }).then((res) =&amp;gt; {
                  {code}...
                }
            }).then((user) =&amp;gt; {
                dispatch(loginSuccess(user)); // Dispatch success action
                navigate('/home');
            }).catch((error) =&amp;gt; {
                dispatch(loginFailure(error)); // Dispatch failure action
                setErrors({ ... });
            });
        }
    });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;Redux Toolkit provides a simpler way to use Redux that helps you avoid boilerplate code and enforces best practices. By structuring your application's state management with slices and utilizing the other tools that Redux Toolkit offers, you can write more efficient, easier-to-understand code.&lt;/p&gt;

&lt;p&gt;Our example of an auth slice is just the tip of the iceberg. There's much more you can do with Redux Toolkit, including creating more complex slices, handling side effects with thunks or sagas, and optimizing re-renders with memoized selectors.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//full code for authSlice.js

import { createSlice } from '@reduxjs/toolkit';

const authSlice = createSlice({
  name: 'auth',
  initialState: {
    user: null,
    isAuthenticated: false,
    isLoading: false,
    updateError: null,
    error: null,
  },
  reducers: {
    loginStart: (state) =&amp;gt; {
      state.isLoading = true;
    },
    loginSuccess: (state, action) =&amp;gt; {
      state.isLoading = false;
      state.isAuthenticated = true;
      state.user = action.payload;
      state.error = null;
    },
    loginFailure: (state, action) =&amp;gt; {
      state.isLoading = false;
      state.error = action.payload;
    },
    logout: (state) =&amp;gt; {
      state.isAuthenticated = false;
      state.user = null;
    },
  },
});

export const { 
  loginStart, 
  loginSuccess, 
  loginFailure, 
  logout
} = authSlice.actions;
export default authSlice.reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;small&gt;&lt;br&gt;
Resources: &lt;a href="https://redux.js.org/"&gt;https://redux.js.org/&lt;/a&gt;&lt;br&gt;
&lt;a href="https://pixallus.com/wp-content/uploads/elementor/thumbs/redux-logo-ofq32q3nphil9qvxfssodliiq4zulp7sagi4e93te0.pnghttps://pixallus.com/wp-content/uploads/elementor/thumbs/redux-logo-ofq32q3nphil9qvxfssodliiq4zulp7sagi4e93te0.png"&gt;img src&lt;/a&gt;&lt;/small&gt;&lt;/p&gt;

</description>
      <category>redux</category>
      <category>react</category>
      <category>javascriptlibraries</category>
      <category>coding</category>
    </item>
    <item>
      <title>Simplify Form Handling with Yup and Formik in React</title>
      <dc:creator>CheriseFoster</dc:creator>
      <pubDate>Tue, 26 Sep 2023 16:19:49 +0000</pubDate>
      <link>https://dev.to/cherisefoster/simplify-form-handling-with-yup-and-formik-in-react-inm</link>
      <guid>https://dev.to/cherisefoster/simplify-form-handling-with-yup-and-formik-in-react-inm</guid>
      <description>&lt;p&gt;Forms are a fundamental part of web applications, and handling them effectively can make or break the user experience. In React, managing forms can be complex, especially when you need to perform client-side validation and submit data to a server. Fortunately, libraries like Yup and Formik come to the rescue, making form management more straightforward, organized, and less error-prone. Let's explore why Yup and Formik are beneficial and walk through an example of how to use them to create a dynamic form in a React application. &lt;/p&gt;




&lt;p&gt;But first....&lt;/p&gt;

&lt;h2&gt;What is Form Handling?&lt;/h2&gt;

&lt;p&gt;Form handling in web development encompasses several essential tasks that ensure a smooth user experience:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;User Interaction:&lt;/strong&gt; Capturing and processing user input through form elements like text fields, checkboxes, and dropdowns.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Form State Management:&lt;/strong&gt; Managing the state of form components, including tracking user input and reflecting changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Validation:&lt;/strong&gt; Ensuring the correctness of user-submitted data by validating it against predefined rules.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Error Handling:&lt;/strong&gt; Providing feedback to users when validation fails or other errors occur during submission.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Submission:&lt;/strong&gt; Sending user data to a server for further processing, often involving HTTP requests or backend interactions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Feedback and Confirmation&lt;/strong&gt;: Confirming to users that their data was received and processed successfully.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resetting or Clearing:&lt;/strong&gt; Offering options to reset or clear the form for a better user experience.&lt;/p&gt;

&lt;p&gt;Form handling in React applications combines libraries like Yup and Formik to streamline and simplify these tasks, resulting in efficient and user-friendly forms.&lt;/p&gt;




&lt;h2&gt;Why Yup and Formik?&lt;/h2&gt;

&lt;p&gt;Let's understand why Yup and Formik are a great combination for handling forms in React:&lt;/p&gt;

&lt;h3&gt;1. Validation with Yup&lt;/h3&gt;

&lt;p&gt;Yup is a powerful and flexible JavaScript schema validation library. It allows you to define schemas for your form data and validate it easily. Some key benefits of using Yup for validation are:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Declarative Schema Definition:&lt;/strong&gt; You can define your data schema in a declarative way using JavaScript objects, making it easy to understand and maintain.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Server and Client-Side Validation:&lt;/strong&gt; Yup supports both server-side and client-side validation, ensuring consistent data validation across your application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Custom Validation Rules:&lt;/strong&gt; You can create custom validation rules and error messages, giving you full control over how your form data is validated.&lt;/p&gt;

&lt;h3&gt;2. Form Management with Formik&lt;/h3&gt;

&lt;p&gt;Formik is a library that simplifies the process of building and managing forms in React. It provides a set of utilities and components that streamline form creation and validation. Formik benefits include:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Form State Management:&lt;/strong&gt; Formik handles the state of your form components, reducing boilerplate code for controlled components and form state management.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Validation Integration:&lt;/strong&gt; Formik integrates seamlessly with validation libraries like Yup, making it easy to validate form data with error messages displayed to users.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Submission Handling:&lt;/strong&gt; Formik simplifies form submission and error handling, making it easy to interact with APIs or perform other actions when the form is submitted.&lt;/p&gt;




&lt;p&gt;To get started, make sure you install yup and Formik and correctly import them to be able to use in your code.&lt;/p&gt;

&lt;p&gt;In my BookHub app, I created a form where a user can upload a book with a title, author, description, image, genre, and status of "read" or "want to read." This component is called "AddBookForm."&lt;br&gt;
First, we define a Yup schema (formSchema) that specifies validation rules for the form fields. In this example, both the "title" and "author" fields are required.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const formSchema = yup.object().shape({
      title: yup.string().required("Must enter a title"),
      author: yup.string().required("Must enter an author"),
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside the AddBookForm function, we initialize Formik by calling useFormik. We provide initial form values, the validation schema, and an onSubmit function that handles form submission:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const formik = useFormik({
      initialValues: {
        title: '',
        author:'',
        description: '',
        image: '',
        genre: '',
        status: 'want-to-read'
      },
      validationSchema: formSchema,
      onSubmit: (values) =&amp;gt; {
        fetch('/books', {
          method:"POST",
          headers: {
            "Content-Type" : "application/json",
          },
          body: JSON.stringify(values)
        }).then((res) =&amp;gt; {
          if(res.ok) {
            res.json().then(book =&amp;gt; {
              addBook(book)
              navigate(`/books/${book.id}`)
            })
          }
        })
      }
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Within the return statement, we create the form elements using standard HTML input elements for each field, including "title" and "author." &lt;br&gt;
For each input field, we connect the value, name, and onChange properties to Formik's state and handlers, ensuring that the form state is controlled by Formik.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return (
      &amp;lt;div className="add-box"&amp;gt;
        &amp;lt;h2&amp;gt;Add Book&amp;lt;/h2&amp;gt;
        &amp;lt;form onSubmit={formik.handleSubmit}&amp;gt;
          &amp;lt;div className="user-box"&amp;gt;
            &amp;lt;input
              type="text"
              name="title"
              value={formik.values.title}
              required
              onChange={formik.handleChange}
            /&amp;gt;
            &amp;lt;label&amp;gt;Title&amp;lt;/label&amp;gt;
          &amp;lt;/div&amp;gt;
//Do this for each input field
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;With Yup handling schema validation and Formik managing the form state and submission, this dynamic form becomes more manageable and less error-prone. The separation of concerns between form state and validation logic leads to cleaner and more maintainable code.&lt;/p&gt;

&lt;p&gt;When working with forms in React, especially complex ones, using libraries like Yup and Formik can significantly simplify the development process. Yup ensures data integrity and validation, while Formik handles form state and submission, resulting in a more organized and efficient codebase.&lt;/p&gt;

</description>
      <category>coding</category>
      <category>formik</category>
      <category>react</category>
      <category>formhandling</category>
    </item>
    <item>
      <title>Creating a database and seeding data with SQLAlchemy</title>
      <dc:creator>CheriseFoster</dc:creator>
      <pubDate>Mon, 17 Jul 2023 04:39:17 +0000</pubDate>
      <link>https://dev.to/cherisefoster/creating-a-database-and-seeding-data-with-sqlalchemy-3cj6</link>
      <guid>https://dev.to/cherisefoster/creating-a-database-and-seeding-data-with-sqlalchemy-3cj6</guid>
      <description>&lt;p&gt;Databases are a critical component for storing and managing data in modern software development. A popular Python library called SQLAlchemy provides an Object-Relational Mapping (ORM) system that simplifies database interactions. In this blog post, we'll explore a code example I created that demonstrates how to create a database using SQLAlchemy, define tables and relationships, and seed it with sample data. &lt;/p&gt;

&lt;h4&gt;But first, what does it mean to "seed" data?&lt;/h4&gt;

&lt;p&gt;Seeding data simply means creating sample instances of data. It involves inserting predefined data into the database tables created.&lt;/p&gt;




&lt;h2&gt;Creating the database schema:&lt;/h2&gt;

&lt;p&gt;To begin, I drew an example on a piece of paper the tables I wanted to create and the columns I wanted to include, as well as defined what type of relationships I wanted my tables to have with each other. It's important to stay organized and have a plan before writing the code. I created a models.py file to build my tables, and a flights.db file so that I can view my tables as actual tables. From there, start by importing necessary modules and defining the database schema using SQLAlchemy's declarative_base() function. &lt;/p&gt;

&lt;p&gt;My schema includes 3 tables: Flight, Passenger, and Reservations. Each table is its own entity, and relationships are established between tables with foreign keys. &lt;/p&gt;

&lt;p&gt;In the code below, I established a Flight class and created a couple of columns I wanted to be on my table with the corresponding data type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Flight(Base):
    __tablename__ = 'flights'

    id = Column(Integer(), primary_key=True)
    airline = Column(String())
    flight_number = Column(Integer())
    origin = Column(String())
    destination = Column(String())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, I used Python's &lt;code&gt;&lt;strong&gt;repr&lt;/strong&gt;&lt;/code&gt; method on classes which defines how an object should be represented when its string representation is requested (such as when the object is printed).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def __repr__(self):
        return (
            f"ID: {self.id}, " \
           + f"Airline: {self.airline}, " \
           + f"Flight Number: {self.flight_number}, " \
           + f"Origin: {self.origin}, " \
           + f"Destination: {self.destination}, " \
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After creating my Flight table, I created a Passenger and Reservation table using the same format and used foreign keys to create a one-to-many relationships between my desired tables. Make sure to import relationship and backref from sqlalchemy.orm to define table relations.&lt;/p&gt;




&lt;h2&gt;Seeding the data:&lt;/h2&gt;

&lt;p&gt;Now that the tables have been created, I created a separate file called seed.py to seed my database with sample data. Import create_engine and sessionmaker, as well as your tables from your models file. Import faker from Faker so that we can generate fake sample data. It doesn't hurt to import random too, just in case you need to generate some random numbers (for a flight number, per say). We are going to write some code to check if the current file is being executed as the main script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if __name__ == "__main__":
    engine = create_engine("sqlite:///flights.db")
    Session = sessionmaker(bind=engine)
    session = Session()

    fake = Faker()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Let's break this down:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;if __name__ == "__main__":&lt;/code&gt; --&amp;gt; 
&lt;code&gt;__name__&lt;/code&gt; holds the name of the current module. The line checks if the current module is the main module being executed.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;engine = create_engine("sqlite:///flights.db"):&lt;/code&gt; --&amp;gt;
This line of code is what creates an SQLAlchemy engine object that will connect to our flight.db database.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Session = sessionmaker(bind=engine)&lt;/code&gt; --&amp;gt;
Here, a session object is created by invoking sessionmaker. This is how we interact with the database.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;session = Session()&lt;/code&gt; --&amp;gt;
We invoke sessionmaker by setting it to an object called session. Using session, we can execute queries and perform database operations. Similarly, &lt;code&gt;fake = Faker()&lt;/code&gt; is invoked and set to an object to be used in our application as well.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;We want to make sure that we write a &lt;code&gt;session&lt;/code&gt; query to clear the database before each seeding, otherwise the database will keep the previous fake data we generated. This should be done for each table that was created:&lt;br&gt;
&lt;code&gt;session.query(Flight).delete()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;For this specific table, I created a list of airlines that contains different airline names as strings, since there is not currently any way to generate fake airline names.&lt;/p&gt;

&lt;p&gt;Create an empty list to append the information we are going to generate, I called mine flights. I want to be able to loop through all of my data, so let's use a for loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for _ in range(75):
        flight = Flight(
            airline = random.choice(list_of_airlines),
            flight_number = random.randint(100, 9999),
            origin = f"{fake.city()}",
            destination = f"{fake.city()}"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since Flight was imported from models.py, I can create a new instance of the Flight class and set it to the "flight" variable. This will create a list of 75 instances of flight information, where it loops through the list of airlines I created, generate a random flight number between the set parameters (told you to import random just in case!), and, using Faker, create fake cities for the origin and destination.&lt;/p&gt;

&lt;p&gt;To finish this code off, we need to push these changes to our database and create instances of data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;session.add(flight)
session.commit()
flights.append(flight)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first line adds the "flight" object to the session, which is an instance of the "Flight" class, and stages the object for insertion into the database. The commit() method persists the changes made within the session. Finally, append the "flight" object to the "flights" list we created.&lt;/p&gt;




&lt;p&gt;Navigate into the flights.db file, and you should be able to see your flights table with data inserted. I viewed my table using the SQLite Viewer extension on VS code:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pNklRkmL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4snqzgg0v5nwp2lwto5q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pNklRkmL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4snqzgg0v5nwp2lwto5q.png" alt="Image description" width="774" height="168"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>React Component Props</title>
      <dc:creator>CheriseFoster</dc:creator>
      <pubDate>Tue, 09 May 2023 22:06:26 +0000</pubDate>
      <link>https://dev.to/cherisefoster/react-component-props-2fcl</link>
      <guid>https://dev.to/cherisefoster/react-component-props-2fcl</guid>
      <description>&lt;p&gt;React is a JavaScript library created and maintained by Meta used for building user interfaces. It is known for its component-based architecture, which allows developers to create reusable and modular code. Props are one of the most important tools to use in React components.&lt;/p&gt;




&lt;h2&gt;What are props?&lt;/h2&gt;

&lt;p&gt;In React, props are a way to pass data from a parent component to a child component. They allow components to be customized and constructed in different ways, without the need to rewrite the component's code.&lt;/p&gt;

&lt;h4&gt;For example:&lt;/h4&gt;

&lt;p&gt;Imagine you have a parent component called "Home" and a child component called "BlogList" that displays a list of blogs. The actual list of blogs is defined in the Home component in the form of an array of objects:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LNLORAxl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b89efkodmf40nckwr75c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LNLORAxl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b89efkodmf40nckwr75c.png" alt="Image description" width="698" height="119"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The BlogList component is the child component that maps over the array of blogs and displays each individual blog. We want to access the blog list array instead of having to copy the code from the Home component into the BlogList component: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--KFwrOSCK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezg2jjxdk2a89ti7li1i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--KFwrOSCK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezg2jjxdk2a89ti7li1i.png" alt="Image description" width="712" height="287"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We pass in props as an argument to BlogList and render the blogs array properties to a constant variable. By doing so, we can access the blogs array and use dot notation to access its key values. &lt;/p&gt;

&lt;p&gt;To make sure that our new, mapped array renders, we need to return the child component, BlogList, in the parent component, Home, and pass the props as attributes:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--m-bhkurN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t61qinhhatcmysu6ukyg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--m-bhkurN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t61qinhhatcmysu6ukyg.png" alt="Image description" width="500" height="57"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Instead of creating a constant variable for blogs and setting it to &lt;code&gt;props.blogs&lt;/code&gt;, another way to access props is to simply pass props as an argument and access the values using dot notation, such as &lt;code&gt;props.blogs.value&lt;/code&gt;. While either will work, there is a way to refactor our code and make it shorter and simpler to read.&lt;/p&gt;




&lt;h2&gt;Destructuring&lt;/h2&gt;

&lt;p&gt;A more effective way to pass in props as an argument is to destructure the props object. Destructuring props takes the keys from the object and creates variables with the same names. The value associated with the key is saved in the corresponding variable so it can be directly accessed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--03vrcGe_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lzfdvqm6ly58dadrtc5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--03vrcGe_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lzfdvqm6ly58dadrtc5.png" alt="Image description" width="728" height="228"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This also makes it easier to tell what props are being passed down to a component. In the above example, we know exactly what values are being accessed into the BlogList component instead of having to look for through the entire component for each prop reference.&lt;/p&gt;

&lt;p&gt;In the Home component, the title attribute is set to a string and passed down as a prop to BlogList as a header for our blogs array:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--M8ZycY3S--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/irt6xoh71rfn4pvvcrdm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--M8ZycY3S--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/irt6xoh71rfn4pvvcrdm.png" alt="Image description" width="425" height="54"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our blog, with a little CSS, would end up looking like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--yRgXj0f2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xlxa0iulqpa5jnx9ow4m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--yRgXj0f2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xlxa0iulqpa5jnx9ow4m.png" alt="Image description" width="800" height="292"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the case that there is no value for a prop that is being passed as an argument, it is possible to set a default value for a prop. In the above example, if there was no title data, we could set the title to default to whatever we saw fit by simply assigning it a default value using an equal sign. (I.e. &lt;code&gt;function BlogList({ title = "whatever" }))&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;Props can be used to customize components in a wide variety of ways. Here are some common examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Setting text, labels, and captions: Props can be used to set the text or label of a component.&lt;/li&gt;

&lt;li&gt;Controlling behavior: Props can be used to control the behavior of a component. For example, you could pass a prop to a Modal component to specify whether it should be displayed or hidden.&lt;/li&gt;

&lt;li&gt;Styling: Props can be used to apply styles to a component. For example, you could pass a prop to a Button component to specify its color or size.&lt;/li&gt;

&lt;li&gt;Data: Props can be used to pass data to a component. As in the above example, you could pass an array of items to a List component to be rendered as a series of list items.&lt;/li&gt;

&lt;/ul&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Props are an important part of React's component-based architecture, as they allow components to be composed and reused in different contexts. By passing different props to a component, you can create variations of that component that can be used in different parts of your application without having to rewrite the component's code.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>InnerText vs. textContent vs. innerHTML : Which one should you use?</title>
      <dc:creator>CheriseFoster</dc:creator>
      <pubDate>Sat, 01 Apr 2023 19:23:40 +0000</pubDate>
      <link>https://dev.to/cherisefoster/innertext-vs-textcontent-vs-innerhtml-which-one-should-you-use-2cp3</link>
      <guid>https://dev.to/cherisefoster/innertext-vs-textcontent-vs-innerhtml-which-one-should-you-use-2cp3</guid>
      <description>&lt;p&gt;Whether you are a beginner or an advanced programmer, you have surely come across the innerText, textContent, and innerHTML properties. Each property can help you change and manipulate your code. But how do you know which to use when they all perform similar operations? &lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Let's break it down:&lt;/strong&gt;
&lt;/h2&gt;




&lt;p&gt;&lt;strong&gt;InnerText&lt;/strong&gt; will show only "human-readable" text. It will not return any styling or hidden elements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TextContent&lt;/strong&gt; returns any and all node elements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;InnerHTML&lt;/strong&gt; allows you to grab the &lt;em&gt;text within the string&lt;/em&gt; of the HTML markup, including any styling or script tags.&lt;/p&gt;




&lt;p&gt;If that still sounds like they are basically doing the same thing, you wouldn't be wrong! They do perform similarly but have subtle differences.&lt;/p&gt;

&lt;p&gt;Let's start out with making a simple &lt;code&gt;div&lt;/code&gt; HTML tag and adding some content: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3-LiJezf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t4otlczp04b47ulzfe7e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3-LiJezf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t4otlczp04b47ulzfe7e.png" alt="Image description" width="611" height="74"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We have some text and some styling included. The &lt;code&gt;strong&lt;/code&gt; tag will bold the word "are", and the &lt;code&gt;em&lt;/code&gt; tag will italicize "differences." We also included 3 spaces between the words "the" and "differences."&lt;br&gt;
Now, let's create a variable in JavaScript so that we can grab the content of our &lt;code&gt;div&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s----TcE3oU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ovttgupsdnxdm54a1qyn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s----TcE3oU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ovttgupsdnxdm54a1qyn.png" alt="Image description" width="505" height="46"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Using innerText:
&lt;/h2&gt;

&lt;p&gt;Recall from above that innerText will return text that is "human-readable". &lt;/p&gt;

&lt;p&gt;&lt;u&gt;Result:&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--KDkUWYNU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qnbuuyim8y14e0w5njga.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--KDkUWYNU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qnbuuyim8y14e0w5njga.png" alt="Image description" width="505" height="65"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The output of &lt;code&gt;getInfo&lt;/code&gt; is all of the &lt;em&gt;text&lt;/em&gt;. Notice how neither of the tags or the spacing shows up when we call &lt;code&gt;getInfo.value&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You should use innerText when you just need to grab THE TEXT without the styling tags or other formatting (the random spaces, for example). Think of innerText as only, &lt;em&gt;you guessed it&lt;/em&gt;, the inner text. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Side note:&lt;/strong&gt; innerText is not supported in Internet Explorer 9 or earlier versions. Because innerText is aware of CSS styling, it also can decrease performance by triggering a reflow. A reflow is when a browser reevaluates page elements when a document is re-rendered. An example of a reflow would be when a browser window is resized. &lt;/p&gt;




&lt;h2&gt;
  
  
  Using textContent
&lt;/h2&gt;

&lt;p&gt;TextContent will grab all of the text and return any styling or script tags and any other formatting.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Result:&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--V8cpFbqm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1m7jm9i1h39claclaa7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--V8cpFbqm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1m7jm9i1h39claclaa7.png" alt="Image description" width="590" height="75"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Notice how textContent grabbed all of the text and the styling, including the spaces. If you want to see what is in the element, then you should use textContent. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Side note:&lt;/strong&gt; textContent will perform better than innerText because it does not trigger a reflow since it is not aware of CSS styling. Also, because its value is not parsed as HTML, textContent can help prevent malicious attacks.&lt;/p&gt;




&lt;h2&gt;
  
  
  Using innerHTML:
&lt;/h2&gt;

&lt;p&gt;InnerHTML will return all of the text, styling tags included, as it is typed in the HTML document. &lt;/p&gt;

&lt;p&gt;&lt;u&gt;Result:&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RivozgpK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8w6hi1ofytfrkjjkh8ae.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RivozgpK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8w6hi1ofytfrkjjkh8ae.png" alt="Image description" width="593" height="68"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What that means is that innerHTML does not change anything, it just returns all of the text as it is in the HTML document.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Side note:&lt;/strong&gt; using innerHTML should be few and far between because it can be a target for malicious code to be inputted.  As long as you are using your own code and not code from any third party, you should be fine using innerHTML, however, try opting for textContent instead.&lt;/p&gt;




&lt;h2&gt;
  
  
  Why would I need to use any of these?
&lt;/h2&gt;




&lt;p&gt;There are a multitude of reasons to use innerText, textContent, or sometimes innerHTML.&lt;br&gt;
As you can see, innerText, textContent, and innerHTML all do very similar things. They all grab the text within the element, but there are slight differences. To recap, innerText will grab strictly the inner text, which means it will grab all of the text that is "normal" to humans. A styling tag such as &lt;code&gt;strong&lt;/code&gt; is not normal text to humans, and it will not show up when using innerText. TextContent will also grab all of the text and whatever styling you put in there. The styling tags will not show as text, but will be executed. Finally, innerHTML will grab everything and return it as it is, styling tags and weird spaces and all. But beware of the safety implications when using innerHTML, and try to avoid using it.&lt;/p&gt;




&lt;p&gt;header photo source: &lt;a href="https://www.goodcore.co.uk/blog/coding-vs-programming/"&gt;https://www.goodcore.co.uk/blog/coding-vs-programming/&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
