Categories
React Answers

How to Update and Merge State Object using React useState Hook?

Sometimes, we want to update and merge state object using React useState hook.

In this article, we’ll look at how to Update and merge state object using React useState hook.

Update and Merge State Object using React useState Hook

To Update and merge state object using React useState hook, we can pass in a function into the state setter function.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount((count) => count + 1);
  };

  return (
    <div>
      <div>{count}</div>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

to create the count state with the useState hook.

And to make sure we update count by incrementing the current count value, we pass in a function that takes the current count value and return the new count value into the setCount state setter function.

Then we set that as the value of the onClick prop of the button to run increment when we click it.

Therefore, when we click the button, we see the count incremented by 1.

Conclusion

To Update and merge state object using React useState hook, we can pass in a function into the state setter function.

Categories
React Answers

How to Detect Page Refresh by Pressing F5 in a React Component?

Sometimes, we want to detect page refresh by pressing F5 in a React component.

In this article, we’ll look at how to detect page refresh by pressing F5 in a React component.

Detect Page Refresh by Pressing F5 in a React Component

To detect page refresh by pressing F5 in a React component, we can use the performance.navigation.type property to check what kind of navigation is done.

If the value is 1, then we refreshed the page manually with the F5 key.

For instance, we write:

import React, { useEffect } from "react";

export default function App() {
  useEffect(() => {
    if (performance.navigation.type === 1) {
      console.log("This page is reloaded");
    } else {
      console.log("This page is not reloaded");
    }
  });

  return <div></div>;
}

We check that the performance.navigation.type value is 1.

If it is, we log 'This page is reloaded'.

This code is in a function in the useEffect hook so that it runs every time rendering is done.

Therefore, when we press F5 to refresh, we should see 'This page is reloaded' logged in the console.

Conclusion

To detect page refresh by pressing F5 in a React component, we can use the performance.navigation.type property to check what kind of navigation is done.

If the value is 1, then we refreshed the page manually with the F5 key.

Categories
React Answers

How to Pass Props to React Components Created with styled-Components?

To pass props to React components created with styled-components, we can interpolate functions into the string that creates the component.

For instance, we write:

import React from "react";
import styled from "@emotion/styled";

const ArrowStyled = styled.div`
  background-color: green;
  width: 24px;
  height: 30px;
  clip-path: polygon(56% 40%, 40% 50%, 55% 63%, 55% 93%, 0% 50%, 56% 9%);
  transform: rotate(${(props) => props.rotates});
`;

const Arrow = ({ rotates }) => {
  return <ArrowStyled rotates={rotates} />;
};

export default function App() {
  return (
    <div>
      <Arrow rotates="90deg" />
    </div>
  );
}

We create the ArrowStyled component with the styled.div tag.

Then string that we pass into the tag has the rotate value set from a prop.

To do this, we pass in a function into the braces to call the function we passed in when we use the component.

The props parameter has the props.

And we return the value of the prop we want to set to set it.

In App, we set the rotates prop to '90deg' to rotate the arrow 90 degrees.

Therefore, we see the rotated arrow on the screen when we render it in App

Categories
React Answers

How to Fix the “React error ‘Failed propType: Invalid prop `children` supplied to `Provider`, expected a single ReactElement'” Error When Developing React Apps with Redux?

Sometimes, we may run into the "React error ‘Failed propType: Invalid prop children supplied to Provider, expected a single ReactElement’" error when developing React apps with Redux.

In this article, we’ll look at how to fix the "React error ‘Failed propType: Invalid prop children supplied to Provider, expected a single ReactElement’" error when developing React apps with Redux.

Fix the "React error ‘Failed propType: Invalid prop children supplied to Provider, expected a single ReactElement’" Error When Developing React Apps with Redux

To fix the "React error ‘Failed propType: Invalid prop children supplied to Provider, expected a single ReactElement’" error when developing React apps with Redux, we should make sure the content in between the Provider tags are React components.

For instance, we write:

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";
import App from "./App";

function counterReducer(state = { value: 0 }, action) {
  switch (action.type) {
    case "counter/incremented":
      return { value: state.value + 1 };
    case "counter/decremented":
      return { value: state.value - 1 };
    default:
      return state;
  }
}

const store = createStore(counterReducer);

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </StrictMode>,
  rootElement
);

App.js

import React from "react";
import { useDispatch, useSelector } from "react-redux";

export default function App() {
  const count = useSelector((state) => state.value);
  const dispatch = useDispatch();

  return (
    <div>
      <button onClick={() => dispatch({ type: "counter/incremented" })}>
        increment
      </button>
      <p>{count}</p>
    </div>
  );
}

to create the counterReducer reducer function.

Then we create the Redux store with createStore.

Next, we wrap Provider around the App component and set store as the value of the store prop.

Then in App, we get the store’s state with the useSelecttor hook.

And we use the useDispatch hook to return the dispatch function, which we call in the onClick handler with an object with the Redux store action type to increment the store’s state.

Therefore, when we click increment, we see count increase by 1.

Conclusion

To fix the "React error ‘Failed propType: Invalid prop children supplied to Provider, expected a single ReactElement’" error when developing React apps with Redux, we should make sure the content in between the Provider tags are React components.

Categories
React Answers

How to Fix the Issue Where You Can’t Change Checkbox State in React?

Sometimes, we run into to the issue where you can’t change checkbox state in React.

In this article, we’ll look at how to fix the issue where you can’t change checkbox state in React.

Fix the Issue Where You Can’t Change Checkbox State in React

To fix the issue where you can’t change checkbox state in React, we should set the checked prop of the checkbox to a state.

Then we update the state’s value when we check or uncheck the checkbox.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [checked, setChecked] = useState(false);

  return (
    <div>
      <input
        type="checkbox"
        checked={checked}
        onChange={(e) => setChecked(e.target.checked)}
      />
    </div>
  );
}

We create the checked state with the useState hook.

Then we set the checked state as the value of the checked prop to make the checkbox update as the state changes.

Finally, to change the state when we click on the checkbox, we set the onChange prop of it to a function that calls setChecked with e.target.checked to update the checked state with the checked value of the checkbox.

Therefore, when we check or uncheck the checkbox, we should see that displayed on the screen.

Conclusion

To fix the issue where you can’t change checkbox state in React, we should set the checked prop of the checkbox to a state.

Then we update the state’s value when we check or uncheck the checkbox.