Categories
React Answers

How to handle null values in React?

Sometimes, we want to handle null values in React.

In this article, we’ll look at how to handle null values in React.

How to handle null values in React?

To handle null values in React, we can use the optional chaining operator.

For instance, we write:

import React from "react";

const customer = {
  name: "Carl",
  details: {
    age: 22,
    location: "Paradise Falls"
  }
};

export default function App() {
  return <div>{customer.details?.address?.city}</div>;
}

We render the value of customer.details?.address?.city without crashing since we a used the optional chaining operator (?.) instead of the regular dot operator for accessing nested properties.

The optional chaining operator returns undefined when it tries to access a property that doesn’t exist or it’s set to null or undefined.

Conclusion

To handle null values in React, we can use the optional chaining operator.

Categories
React Answers

How to fix the anchor tag isn’t calling the onClick function issue in React?

Sometimes, we want to fix the anchor tag isn’t calling the onClick function issue in React.

In this article, we’ll look at how to fix the anchor tag isn’t calling the onClick function issue in React.

How to fix the anchor tag isn’t calling the onClick function issue in React?

To fix the anchor tag isn’t calling the onClick function issue in React, we can call e.preventDefault in our click event handler function.

For instance, we write:

import React from "react";

export default function App() {
  const onClick = (e) => {
    e.preventDefault();
    console.log("clicked");
  };

  return (
    <a href="https:/example.com" onClick={onClick}>
      click me
    </a>
  );
}

to add the onClick function that calls e.preventDefault to stop the default behavior of going to the page with the URL set as the value of the href attribute.

And then we set the onClick prop of the a element to the onClick function.

As a result, we see 'clicked' logged in the console instead of going to https://example.com when we click on the link.

Conclusion

To fix the anchor tag isn’t calling the onClick function issue in React, we can call e.preventDefault in our click event handler function.

Categories
React Answers

How to call a method from another class component in React.js?

Sometimes, we want to call a method from another class component in React.js.

In this article, we’ll look at how to call a method from another class component in React.js.

How to call a method from another class component in React.js?

To call a method from another class component in React.js, we can pass the class method as a prop to a child component.

For instance, we write:

import React, { Component } from "react";

class Class1 extends Component {
  render() {
    const { onClick } = this.props;
    return <div onClick={onClick}>click me</div>;
  }
}

class Class2 extends Component {
  onClick = () => {
    console.log("class 2 click");
  };

  render() {
    return <Class1 onClick={this.onClick} />;
  }
}

export default function App() {
  return <Class2 />;
}

We have components Class1 and Class2.

And Class1 is a child of Class2.

To pass the onClick method as a prop to Class1, we add onClick={this.onClick}.

Then in Class1, we get the onClick method from this.props and set that as the value of the onClick prop of the div.

Now when we click on the div, we see 'class 2 click' logged.

Conclusion

To call a method from another class component in React.js, we can pass the class method as a prop to a child component.

Categories
React Answers

How to use escape characters in JSX React components?

Sometimes, we want to use escape characters in JSX React components.

In this article, we’ll look at how to use escape characters in JSX React components.

How to use escape characters in JSX React components?

To use escape characters in JSX React components, we can use the same ones as plain JavaScript.

JavaScript escape characters include:

  • ' single quote
  • " double quote
  • \ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed

We can also use HTML escape characters in JSX.

To do so, we can put them directly between the element’s tags.

For instance, we can write:

import React from "react";

export default function App() {
  return <div>First &middot; Second</div>;
}

Then we get ‘First · Second’ as a result.

Conclusion

To use escape characters in JSX React components, we can use the same ones as plain JavaScript.

We can also use HTML escape characters in JSX.

To do so, we can put them directly between the element’s tags.

Categories
React Answers

How to run the Formik setSubmitting() outside the submit handler with React?

Sometimes, we want to run the Formik setSubmitting outside the submit handler with React.

In this article, we’ll look at how to run the Formik setSubmitting outside the submit handler with React.

How to run the Formike setSubmitting() outside the submit handler with React?

To run the Formik setSubmitting outside the submit handler with React, we can get the setSubmitting function from the render prop parameter and call it.

For instance, we write:

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

export default function App() {
  return (
    <div>
      <Formik
        ref={formikRef}
        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 }) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 400);
        }}
      >
        {({
          values,
          errors,
          touched,
          handleChange,
          handleBlur,
          handleSubmit,
          isSubmitting,
          setSubmitting
        }) => (
          <form onSubmit={handleSubmit}>
            <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>
            <button type="button" onClick={() => setSubmitting(false)}>
              reset
            </button>
          </form>
        )}
      </Formik>
    </div>
  );
}

We create a simple form with the Formik component.

We set the initial form values with initialValues.

And we set the validate prop to a function that checks the entered values, which are obtained from the values parameter.

The onSubmit prop is set to the form submit event handler.

We set the render prop to a function that returns a form.

We set the onSubmit prop to handleSubmit to run the function that we set as the value of the onSubmit prop.

From the render prop function, we get the setSubmitting function from the prop object parameter.

And we use handleBlur as the value of onBlur and the properties from values as the value of the value prop of the inputs.

The properties in values is determined by the value of the name attribute of each input.

Then we call that in the click event handler that we set as the value of the onClick prop of the reset button.

Conclusion

To run the Formik setSubmitting outside the submit handler with React, we can get the setSubmitting function from the render prop parameter and call it.