Categories
React Answers

How to Use the Switch Statement Inside a React Component?

Sometimes, we want to use switch statements inside a React component.

In this article, we’ll look at how to use switch statements inside a React component.

Use the Switch Statement Inside a React Component

We can use switch statements inside a React component as we do with plain JavaScript.

For instance, we can write:

import React from "react";

const Foo = ({ val }) => {
  switch (val) {
    case "bar":
      return "bar";
    default:
      return "foo";
  }
};

export default function App() {
  return (
    <>
      <Foo val="bar" />
      <Foo val="abc" />
    </>
  );
}

We have the Foo component that takes the val prop.

And we use the switch statement to render the content we want to render with the return statement.

So if we set val to bar we render bar .

Otherwise, we render foo .

Conclusion

We can use switch statements inside a React component as we do with plain JavaScript.

Categories
React Answers

How to Add Prop Validation for Date Objects with React?

Sometimes, we want to add prop validation for date objects with React.

In this article, we’ll look at how to add prop validation for date objects with React.

Add Prop Validation for Date Objects with React

To add prop validation for date objects with React, we can use the prop-types library.

To install it, we run:

npm i prop-types

Then we can use it by writing:

import React from "react";
import PropTypes from "prop-types";

const DateDisplay = ({ date }) => <p>{date.toString()}</p>;

DateDisplay.propTypes = {
  date: PropTypes.instanceOf(Date)
};

export default function App() {
  return <DateDisplay date={new Date(2021, 1, 1)} />;
}

We create the DateDisplay component that takes the date prop.

And to validate it, we set the propTypes property of it to an object with the date property.

We set the allowed type of date to only be a Date instance by writing:

PropTypes.instanceOf(Date)

Now we set the date prop to anything other than a Date instance, we’ll get an error in the console.

Conclusion

To add prop validation for date objects with React, we can use the prop-types library.

Categories
React Answers

How to Convert HTML Strings to JSX with React?

Sometimes, we want to convert HTML Strings to JSX with React.

In this article, we’ll look at how to convert HTML Strings to JSX with React.

Convert HTML Strings to JSX with React

There’re several ways to convert HTML Strings to JSX with React.

One way is to put the string in between curly braces in our component.

For instance, we can write:

import React from "react";

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

to put a string in between the curly braces to render it.

Another way is to put the string in an array with other strings or JSX code.

For instance, we can write:

import React from "react";

export default function App() {
  return <div>{["First ", <span key="1">&middot;</span>, " Second"]}</div>;
}

We add the span element as the 2nd element between 2 strings.

Any element or component should have a key prop, so we set the key prop of the span so React can keep track of it.

Finally, we can use the dangerouslySetInnerHTML prop render an HTML string as HTML in our component:

import React from "react";

export default function App() {
  return <div dangerouslySetInnerHTML={{ __html: "First &middot; Second" }} />;
}

We pass in an object with the __html property containing the text to render it.

Conclusion

There’re several ways to convert HTML Strings to JSX with React.

One way is to put the string in between curly braces in our component.

Another way is to put the string in an array with other strings or JSX code.

Finally, we can use the dangerouslySetInnerHTML prop render an HTML string as HTML in our component.

Categories
React Answers

How to Get Form Data in React?

Sometimes, we want to get form data from form fields in React.

In this article, we’ll look at how to get form data from form fields in React.

Get Form Data in React

To get form data from form fields in React, we can store the input values in states and then get the values when we need them.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleEmailChange = (e) => {
    setEmail(e.target.value);
  };

  const handlePasswordChange = (e) => {
    setPassword(e.target.value);
  };

  const handleLogin = () => {
    console.log(email, password);
  };

  return (
    <form>
      <input
        type="text"
        name="email"
        placeholder="Email"
        value={email}
        onChange={handleEmailChange}
      />
      <input
        type="password"
        name="password"
        placeholder="Password"
        value={password}
        onChange={handlePasswordChange}
      />
      <button type="button" onClick={handleLogin}>
        Login
      </button>
    </form>
  );
}

We defined the email and password states with the useState hooks.

Then we defined the handleEmailChange and handlePasswordChange functions that calls setEmail and setPassword with e.target.value to set the email and password states respectively.

e.target.value has the inputted values from the input fields.

Next, we add 2 input fields that have the value and onChange props set.

value is set to the states that have the input values.

onChange is set to change event handler functions that’s used to set the email and password states to the inputted values.

Then we add a button with the onClick prop sets to the handleLogin function that logs the email and password values that are typed in before clicking the button.

Conclusion

To get form data from form fields in React, we can store the input values in states and then get the values when we need them.

Categories
React Answers

How to Combine Multiple Inline Style Objects in React?

Sometimes, we want to combine multiple inline style objects in React.

In this article, we’ll look at how to combine multiple inline style objects in React.

Combine Multiple Inline Style Objects in React

We can use the spread operator to combine multiple inline style objects in React.

For instance, we can write:

import React from "react";

const baseStyle = {
  color: "red"
};

const enhancedStyle = {
  fontSize: "38px"
};

export default function App() {
  return <h1 style={{ ...baseStyle, ...enhancedStyle }}>hello world</h1>;
}

to combine the inline styles from the baseStyle and enhancedStyle objects with the spread operator.

The style properties are spread into a new object which is passed in as the value of the style prop.

Therefore, we should see red text in 38 point size font displayed.

Conclusion

We can use the spread operator to combine multiple inline style objects in React.