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.

Categories
React Answers

How to access styles of an element from React?

Sometimes, we want to access styles of an element from React.

In this article, we’ll look at how to access styles of an element from React.

How to access styles of an element from React?

To access styles of an element from React, we can assign a ref to the element that we want to get the styles for.

And then we can use the window.getComputedStyle method to get the style from the element’s ref.

For instance, we write:

import React, { useEffect, useRef } from "react";

export default function App() {
  const ref = useRef();
  useEffect(() => {
    const computed = window
      .getComputedStyle(ref.current)
      .getPropertyValue("border-radius");
    console.log(computed);
  }, []);

  return (
    <div ref={ref} style={{ borderRadius: "5px" }}>
      hello world
    </div>
  );
}

We create a ref with the useRef hook.

Then we assign the ref to the div.

Next, we get the border-radius style of the div when the div is rendered by using:

const computed = window
   .getComputedStyle(ref.current)
   .getPropertyValue("border-radius");

We put the code in the useEffect callback so it’ll run when the component is mounted.

As a result, we get that computed is 5px since we set the borderRadius of the div to 5px.

Conclusion

To access styles of an element from React, we can assign a ref to the element that we want to get the styles for.

And then we can use the window.getComputedStyle method to get the style from the element’s ref.