Categories
React Answers

How to set z-index on a React component?

Sometimes, we want to set z-index on a React component.

In this article, we’ll look at how to set z-index on a React component.

How to set z-index on a React component?

To set z-index on a React component, we set the position and zIndex properties of a component.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <>
      <div style={{ position: "relative", zIndex: "1" }}>bottom</div>
      <div style={{ position: "relative", zIndex: "2" }}>top</div>{" "}
    </>
  );
}

We set the position and zIndex properties to set the z-index of the divs.

The z-index property are enforced if position is set to absolute, relative, sticky or fixed.

Conclusion

To set z-index on a React component, we set the position and zIndex properties of a component.

Categories
React Answers

How to add links to a React Router route with React-Bootstrap?

Sometimes, we want to add links to a React Router route with React-Bootstrap.

In this article, we’ll look at how to add links to a React Router route with React-Bootstrap.

How to add links to a React Router route with React-Bootstrap?

To add links to a React Router route with React-Bootstrap, we can use the Nav.Link component.

For instance, we write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Nav, Navbar } from "react-bootstrap";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  NavLink
} from "react-router-dom";

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

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

const Links = () => {
  return (
    <Navbar>
      <Navbar.Brand as={NavLink} to="/">
        Brand link
      </Navbar.Brand>
      <Nav>
        <Nav.Link as={NavLink} to="/" exact>
          Home
        </Nav.Link>
        <Nav.Link as={NavLink} to="/foo">
          Foo
        </Nav.Link>
        <Nav.Link as={NavLink} to="/bar">
          Bar
        </Nav.Link>
      </Nav>
    </Navbar>
  );
};

export default function App() {
  return (
    <Router>
      <div>
        <Links />
        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

to add links to the /foo and /bar routes with Nav.Link.

We set the as prop to the React Bootstrap’s NavLink component so that the link is rendered by React Bootstrap and it links to the route defined with React Router.

We set the to prop of each Nav.Link to the route we want to load when we click on the link.

Therefore, we should see ‘foo’ and ‘bar’ when we click on Foo and Bar respectively.

Conclusion

To add links to a React Router route with React-Bootstrap, we can use the Nav.Link component.

Categories
React Answers

How to listen to keypress for document in React?

Sometimes, we want to listen to keypress for document in React.

In this article, we’ll look at how to listen to keypress for document in React.

How to listen to keypress for document in React?

To listen to keypress for document in React, we can call document.addEventListener in the useEffect hook callback.

For instance, we write:

import React, { useEffect } from "react";

export default function App() {
  const handleKeyDown = (e) => {
    console.log(e.key);
  };

  useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);

    return () => document.removeEventListener("keydown", handleKeyDown);
  }, []);

  return <div></div>;
}

In the useEffect callback, we call document.addEventListener with 'keydown' and the handleKeyDown function.

Next, we return a function that calls document.removeEventListener with the same arguments to remove the event listener when App is unmounted.

In handleKeyDown, we get the key that’s pressed with the e.key property.

Now when we’re focused on the window and the press keys on the keyboard, we should see the key value logged.

Conclusion

To listen to keypress for document in React, we can call document.addEventListener in the useEffect hook callback.

Categories
React Answers

How to properly use Formik’s setStatus method?

Sometimes, we want to properly use Formik’s setStatus method.

In this article, we’ll look at how to properly use Formik’s setStatus method.

How to properly use Formik’s setStatus method?

To properly use Formik’s setStatus method, we can call it in the submit handler.

For instance, we write:

import React from "react";
import { Formik } from "formik";

export default function App() {
  return (
    <Formik
      initialValues={{ email: "", password: "" }}
      validate={(values) => {
        const errors = {};
        if (!values.email) {
          errors.email = "Required";
        } else if (
          !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
        ) {
          errors.email = "Invalid email address";
        }
        return errors;
      }}
      onSubmit={(values, { setSubmitting, setStatus }) => {
        setStatus();
        setTimeout(() => {
          console.log(JSON.stringify(values, null, 2));
          setSubmitting(false);
          setStatus("success");
        }, 1000);
      }}
    >
      {({
        values,
        errors,
        touched,
        handleChange,
        handleBlur,
        handleSubmit,
        isSubmitting,
        status
      }) => (
        <form onSubmit={handleSubmit}>
          {status}
          <input
            type="email"
            name="email"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.email}
          />
          {errors.email && touched.email && errors.email}
          <input
            type="password"
            name="password"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.password}
          />
          {errors.password && touched.password && errors.password}
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </form>
      )}
    </Formik>
  );
}

We have a form that we create with the Formik component.

We have the validate prop set to a function that returns any errors in the input values.

The onSubmit prop is set to a function that calls setStatus to set the status property in the render prop’s object parameter.

We display status above the inputs.

The values property has the input values of each field.

We set the name attribute of each input to set the properties with the names of the names attributes of the values object to the input value of the field with the given name attribute.

Now when the onSubmit function is run, we should see ‘success’ displayed on the left of the form.

Conclusion

To properly use Formik’s setStatus method, we can call it in the submit handler.

Categories
React Answers

How to forward multiple refs with React?

Sometimes, we want to forward multiple refs with React.

In this article, we’ll look at how to forward multiple refs with React.

How to forward multiple refs with React?

To forward multiple refs with React, we can pass in the refs in an object.

For instance, we write:

import React, { useRef } from "react";

const Child = React.forwardRef((props, ref) => {
  const { ref1, ref2 } = ref.current;
  console.log(ref1, ref2);

  return (
    <>
      <p ref={ref1}>foo</p>
      <p ref={ref2}>bar</p>
    </>
  );
});

export default function App() {
  const ref1 = useRef();
  const ref2 = useRef();
  const ref = useRef({ ref1, ref2 });

  return <Child ref={ref} />;
}

We have the Child component that accepts refs since we created it by calling forwardRef with the component function.

In the function, we destructure the refs we pass in by using:

const { ref1, ref2 } = ref.current;

Then we assign ref1 and ref2 to the p elements.

In App, we create the refs with the useRef hook.

We create ref by calling useRef with an object created from the existing refs.

And finally, we set the ref prop of the Child to ref.

Therefore, from the console log, we can see ref1 and ref2‘s current property are assigned to the paragraph elements in Child.

Conclusion

To forward multiple refs with React, we can pass in the refs in an object.