Categories
React Answers

How to Conditionally Wrap a React Component?

Sometimes, we want to conditionally wrap a React component.

In this article, we’ll look at how to conditionally wrap a React component.

Conditionally Wrap a React Component

To conditionally wrap a React component, we can create our own higher-order component.

For instance, we write:

import React from "react";

const WithLink = ({ link, className, children }) =>
  link ? (
    <a href={link} className={className}>
      {children}
    </a>
  ) : (
    children
  );

export default function App() {
  return (
    <>
      <p>
        <WithLink link="https://example.com" className="link">
          example
        </WithLink>
      </p>
      <p>
        <WithLink className="link">example</WithLink>
      </p>
    </>
  );
}

We create the WithLink component that takes the link, className and children props.

If link is set, then we return an a element with children as its content.

Otherwise, we return children as is.

In App, we use WithLink with and without the link prop.

If link is set, then we see a link rendered.

Otherwise, the content inside WithLink is rendered as is.

Conclusion

To conditionally wrap a React component, we can create our own higher-order component.

Categories
React Answers

How to Repeat an Element n Times Using JSX?

Sometimes, we want to repeat an element n times using JSX.

In this article, we’ll look at how to repeat an element n times using JSX.

Repeat an Element n Times Using JSX

To repeat an element n times using JSX, we can create an array with n empty slots with the Array constructor.

Then we call map to map that into the element we want to display.

For instance, we write:

import React from "react";

const n = 8;

export default function App() {
  return (
    <>
      {[...Array(n)].map((e, i) => (
        <span className="diamond" key={i}>
          ♦
        </span>
      ))}
    </>
  );
}

to repeat the diamond character 8 times.

We set n to 8.

Then we pass that in as the argument of Array to create an array with 8 empty slots.

Next, we spread that into an array to return an array with 8 undefined entries.

Finally, we call map with a callback that returns a span with the diamond in it.

Conclusion

To repeat an element n times using JSX, we can create an array with n empty slots with the Array constructor.

Then we call map to map that into the element we want to display.

Categories
React Answers

How to Add Prop Type Validation with PropTypes to a Functional Stateless React Component?

Sometimes, we want to add prop type validation with PropTypes to a functional stateless React component.

In this article, we’ll look at how to add prop type validation with PropTypes to a functional stateless React component.

Add Prop Type Validation with PropTypes to a Functional Stateless React Component

To add prop type validation with PropTypes to a functional stateless React component, we can set the propRTypes property of the functional stateless component to an object that has the prop names as the keys and the corresponding prop data types as the values.

For example, we write:

import React, { useState } from "react";
import PropTypes from "prop-types";

const Header = ({ name }) => <div>hi {name}</div>;

Header.propTypes = {
  name: PropTypes.string
};

Header.defaultProps = {
  name: "james"
};

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

We create the Header component that takes the name prop.

And we validate the data type of the name prop with:

Header.propTypes = {
  name: PropTypes.string
};

We make React check that name should be a string with the object above.

And then we set the default value of name with:

Header.defaultProps = {
  name: "james"
};

We set the default value of name to 'james'.

Therefore, since we passed nothing for name in App, we see ‘hi james’ displayed.

Conclusion

To add prop type validation with PropTypes to a functional stateless React component, we can set the propRTypes property of the functional stateless component to an object that has the prop names as the keys and the corresponding prop data types as the values.

Categories
React Answers

How to Toggle a Boolean State in a React Component?

Sometimes, we want to toggle a boolean state in a React component.

In this article, we’ll look at how to toggle a boolean state in a React component.

Toggle a Boolean State in a React Component

To toggle a boolean state in a React component, we can pass in a function that takes the existing value of the state and returns the next state into a state setter function.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [check, setCheck] = useState(false);

  return (
    <>
      <div>
        <button onClick={() => setCheck((prevCheck) => !prevCheck)}>
          {check.toString()}
        </button>
      </div>
    </>
  );
}

We call the useState hook to create the check state.

Then we pass in a function that calls setCheck with a callback that takes the prevCheck parameter, which has the current value of the check state, as the value of the onClick prop.

And we return the new value of the check state as the return value.

Therefore, when we click the button, we see check toggle between true and false.

Conclusion

To toggle a boolean state in a React component, we can pass in a function that takes the existing value of the state and returns the next state into a state setter function.

Categories
React Answers

How to Fix the ‘Uncaught ReferenceError: React is not defined’ Error When Developing React Apps?

Sometimes, we want to fix the ‘Uncaught ReferenceError: React is not defined’ error when developing React apps.

In this article, we’ll look at how to fix the ‘Uncaught ReferenceError: React is not defined’ error when developing React apps.

Fix the ‘Uncaught ReferenceError: React is not defined’ Error When Developing React Apps

To fix the ‘Uncaught ReferenceError: React is not defined’ error when developing React apps, we can add the 'react' property to the externals property in webpack.config.json.

To do this, we write:

externals: {
    'react': 'React'
},

to tell Webpack that React a global variable.

Also, we can add import React from 'react'; to the top of each component file to fix the error.

Conclusion

To fix the ‘Uncaught ReferenceError: React is not defined’ error when developing React apps, we can add the 'react' property to the externals property in webpack.config.json.

Also, we can add import React from 'react'; to the top of each component file to fix the error.