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.

Categories
React Answers

How to Pretty Print JSON within React Components?

Sometimes, we want to pretty print JSON within React components.

In this article, we’ll look at how to pretty print JSON within React components.

Pretty Print JSON within React Components

To pretty print JSON within React components, we call call JSON.stringify with extra arguments.

For instance, we write:

import React from "react";

const data = { a: 1, b: 2 };

export default function App() {
  return (
    <>
      <div>
        <pre>{JSON.stringify(data, null, 2)}</pre>
      </div>
    </>
  );
}

to call JSON.stringify with 2 as the 3rd argument.

This will make the returned JSON string have 2 spaces for indentation at each level.

Therefore, we should see:

{
  "a": 1,
  "b": 2
}

rendered.

Conclusion

To pretty print JSON within React components, we call call JSON.stringify with extra arguments.

Categories
React Answers

How to Fix the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ Error When Developing React Apps?

Sometimes, we may run into the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ error when developing React apps.

In this article, we’ll look at how to fix the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ error when developing React apps.

Fix the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ Error When Developing React Apps?

To fix the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ error when developing React apps, we should call hook functions only in function components at the top level.

They also shouldn’t be called inside async code.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [val, setVal] = useState("green");

  return (
    <>
      <button onClick={() => setVal(val === "green" ? "red" : "green")}>
        click me
      </button>
      <p>{val}</p>
    </>
  );
}

to call the useState gook at the top level.

And then we can use its returned values in the JSX code.

The hooks must be called at the top level and in synchronous code only so that React can keep track of the order the hooks are called.

Conclusion

To fix the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ error when developing React apps, we should call hook functions only in function components at the top level.