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.

Categories
React Answers

How to Detect When a User Scrolls to Bottom of div with React?

Sometimes, we want to detect when a user scrolls to bottom of div with React.

In this article, we’ll look at how to detect when a user scrolls to bottom of div with React.

Detect When a User Scrolls to Bottom of div with React

To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element.

For instance, we write:

import React, { useRef } from "react";

export default function App() {
  const listInnerRef = useRef();

  const onScroll = () => {
    if (listInnerRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = listInnerRef.current;
      if (scrollTop + clientHeight === scrollHeight) {
        console.log("reached bottom");
      }
    }
  };

  return (
    <div>
      <div
        onScroll={onScroll}
        ref={listInnerRef}
        style={{ height: "200px", overflowY: "auto" }}
      >
        {Array(200)
          .fill()
          .map((_, i) => {
            return <p key={i}>{i}</p>;
          })}
      </div>
    </div>
  );
}

We call the useRef hook to create a ref and we assign the returned ref to the inner div, which is scrollable.

Then we define the onScroll function that destructures the scrollTop, clientHeight and scrollHeight properties from the scrollable div.

The scrollable div element is stored in listInnerRef.current since we assigned the ref to it.

Then we add an if statement to compare scrollTop + clientHeight to scollHeight.

We make the div scrollable by setting it to a fixed height and set overflowY to 'auto'.

And we set the onScroll prop to onScroll so the onScroll function runs when we scroll the scrollable div.

If they’re the same, then we know we reached the bottom.

Therefore, if we scroll to the bottom of the scrollable div, we should see 'reached bottom' logged.

Conclusion

To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element.

Categories
React Answers

How to Set HTML body Element Styles from within a React Component?

Sometimes, we want to set HTML body element styles from within a React component.

In this article, we’ll look at how to set HTML body element styles from within a React component.

Set HTML body Element Styles from within a React Component

To set HTML body element styles from within a React component, we can set the document.body.style properties to the values we want.

For instance, we write:

import React, { useEffect } from "react";

export default function App() {
  useEffect(() => {
    document.body.style.backgroundColor = "yellow";

    return () => {
      document.body.style.backgroundColor = "white";
    };
  }, []);
  return <div>hello world</div>;
}

We set document.body.style.backgroundColor to the value we want in the useEffect hook so that it’s set to the value we want when the component is rendered.

And we set the 2nd argument of the hook to an empty array so that the background color is only set when the component is first rendered.

Also, we return a function that sets the background color when we unmount the component in the useEffect callback.

Now we should see the page has a yellow background.

Conclusion

To set HTML body element styles from within a React component, we can set the document.body.style properties to the values we want.