Categories
React Answers

How to add scroll event listeners in a React component?

Sometimes, we want to add scroll event listeners in a React component.

In this article, we’ll look at how to add scroll event listeners in a React component.

How to add scroll event listeners in a React component?

To add scroll event listeners in a React component, we can set the onScroll prop of an element to an event handler function.

For instance, we write:

import React from "react";

export default function App() {
  const onScroll = (e) => console.log(e);

  return (
    <div onScroll={onScroll} style={{ height: 50, overflowY: "scroll" }}>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lobortis,
      elit at varius euismod, felis felis scelerisque lacus, at laoreet neque
      nisi sit amet arcu. Nullam placerat porttitor justo, non pretium justo
      fringilla aliquam. Vivamus vel odio imperdiet nisi faucibus hendrerit.
      Nunc finibus nisi faucibus nulla ultrices, nec consequat tellus
      condimentum. Cras et pulvinar augue. Aliquam laoreet dolor ultrices mi
      laoreet, in laoreet enim venenatis. Sed faucibus ipsum nec quam iaculis,
    </div>
  );
}

We create the onScroll function that logs the scroll event object.

Then we assign the onScroll function as the value of the onScroll prop of the div.

Now when we scroll up and down, we should see the scroll event object logged.

Conclusion

To add scroll event listeners in a React component, we can set the onScroll prop of an element to an event handler function.

Categories
React Answers

How to switch between pages in React?

Sometimes, we want to switch between pages in React.

In this article, we’ll look at how to switch between pages in React.

How to switch between pages in React?

To switch between pages in React, we can use the React Router package.

To install it, we run:

npm i react-router

Then to use it, we write:

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  NavLink
} from "react-router-dom";

const Foo = () => {
  return <p>foo</p>;
};

const Bar = () => {
  return <p>bar</p>;
};

export default function App() {
  return (
    <Router>
      <style>{`.is-active { font-weight: bold }`}</style>
      <div>
        <ul>
          <li>
            <NavLink to="/foo" activeClassName="is-active">
              foo
            </NavLink>
          </li>
          <li>
            <NavLink to="/bar" activeClassName="is-active">
              bar
            </NavLink>
          </li>
        </ul>

        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

First, we create the Foo and Bar page components.

Next, we add the Routes to map the URLs to the components to render.

Then we add the NavLinks to add links that lets us set the class name of the active link.

We set activeClassName to a string for the class name of the active link.

In the style element, we add a string to style anything with the is-active class by making the font bold.

Therefore, when we click on the links, we’ll see the link for the current page bolded.

Conclusion

To switch between pages in React, we can use the React Router package.

Categories
React Answers

How to style react-datepicker?

Sometimes, we want to style react-datepicker.

In this article, we’ll look at how to style react-datepicker.

How to style react-datepicker?

To style react-datepicker, we can set the wrapperClassName prop to a class name.

And then we can apply styles to that class name.

For instance, we write:

import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

export default function App() {
  return (
    <div>
      <style>
        {`.date-picker input {
          width: 100%
      }`}
      </style>
      <DatePicker wrapperClassName="date-picker" />
    </div>
  );
}

We set wrapperClassName to 'date-picker'.

And then we add some styles to the class in the style element.

We set the width of the input to 100%, so it’ll fill the whole container.

As a result, we should see the date picker input fill the whole container.

Conclusion

To style react-datepicker, we can set the wrapperClassName prop to a class name.

And then we can apply styles to that class name.

Categories
React Answers

How to update a state when state is an array of objects with React?

Sometimes, we want to update a state when state is an array of objects with React.

In this article, we’ll look at how to update a state when state is an array of objects with React.

How to update a state when state is an array of objects with React?

To update a state when state is an array of objects with React, we can return a new array with the values we want in the state setter function’s callback.

For instance, we write:

import React, { useState } from "react";

const items = [
  { id: 1, num: 1 },
  { id: 2, num: 2 },
  { id: 3, num: 3 }
];

export default function App() {
  const [vals, setVals] = useState(items);
  const onClick = () => {
    setVals((vals) => {
      return [
        ...vals.slice(0, 1),
        { id: 2, num: Math.random() * 100 },
        ...vals.slice(2)
      ];
    });
  };

  return (
    <div>
      <button onClick={onClick}>update</button>
      {vals.map((v) => {
        return <p key={v.id}>{v.num}</p>;
      })}
    </div>
  );
}

We define the vals state with the useState hook.

Then we define the onClick function that calls setVals with a callback that takes the existing vals array value as the parameter.

And then we return the new value for the vals state by updating the 2nd entry of it and keeping the rest the same.

We spread the existing elements returned by slice and only change the num property of the 2nd entry.

Finally, we set the onClick prop of the button to onClick so vals is updated when we click it.

And we render the num in vals with vals.map.

Conclusion

To update a state when state is an array of objects with React, we can return a new array with the values we want in the state setter function’s callback.

Categories
React Answers

How to specify styles of children on parents hover with Styled-Components?

Sometimes, we want to specify styles of children on parents hover with Styled-Components.

In this article, we’ll look at how to specify styles of children on parents hover with Styled-Components.

How to specify styles of children on parents hover with Styled-Components?

To specify styles of children on parents hover with Styled-Components, we can use the &:hover pseudo-selector to specify the styles rendered on hovering on the parent element.

For instance, we write:

import React from "react";
import styled from "styled-components";

const Container = styled.div`
  width: 100px;
  height: 100px;
  &:hover #child {
    background: green;
  }
`;

const Child = styled.div`
  width: fit-content;
  height: fit-content;
`;

export default function App() {
  return (
    <Container>
      <Child id="child">hello world</Child>
    </Container>
  );
}

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

Then we specify the styles applied to the element with ID child inside the Container with:

&:hover #child {
  background: green;
}

Then in App, we render the Container with Child inside it.

As a result, when we hover over the container element, we see the background of the child element turn green.

Conclusion

To specify styles of children on parents hover with Styled-Components, we can use the &:hover pseudo-selector to specify the styles rendered on hovering on the parent element.