Categories
React Answers

How to fix ‘Switch’ is not exported from ‘react-router-dom’ import error with React Router?

If we are encountering an “Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’” message, it’s likely because we are trying to import the Switch component from react-router-dom, but it doesn’t exist.

Starting from React Router v6, Switch has been removed, and its functionality has been integrated into the Routes component. To achieve the same functionality as Switch from React Router v5 in React Router v6, weneed to use the Routes component with the element prop.

Here’s how we can refactor our code:

In React Router v5 we write

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
        <Route path="/" component={Home} />
      </Switch>
    </Router>
  );
}

Using React Router v6 we write

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
        <Route path="/" element={<Home />} />
      </Routes>
    </Router>
  );
}

In this example, the Routes component is used instead of Switch, and each Route component includes the element prop, which specifies the component to render for that route. Make sure our adjust our code accordingly based on our React Router version.

Categories
React Answers

How to specify a port to run a create-react-app based project?

To specify a port to run a create-react-app based project, we can use the PORT environment variable. Here’s how we can do it:

  1. Open our project’s package.json file.
  2. Find the "scripts" section.
  3. Modify the "start" script to include the PORT environment variable. It should look something like this:
"scripts": {
  "start": "PORT=3001 react-scripts start",
  ...
}

In this example, the port is set to 3001, but we can replace it with any port number we prefer.

Alternatively, we can specify the port directly in the command line when we run the npm start command:

PORT=3001 npm start

This will start our create-react-app based project on port 3001. Adjust the port number as needed for our project.

Categories
React Answers

When to use JSX.Element vs ReactNode vs ReactElement?

In React, JSX.Element,ReactNode, and ReactElement are types used to represent different aspects of React components and JSX elements.

JSX.Element

JSX.Element represents the result of compiling JSX code.

We would use JSX.Element when you want to specify the return type of a function component that returns JSX.

Example:

import React from 'react';

function MyComponent(): JSX.Element {
  return <div>Hello, world!</div>;
}

ReactNode

Definition: ReactNode represents a renderable child in React. It can be a React element, string, number, array, fragment, or boolean.

We would use ReactNode when you want to accept any renderable content as children in your component, regardless of its type.

Example:

import React, { ReactNode } from 'react';

interface Props {
  children: ReactNode;
}

function MyComponent({ children }: Props) {
  return <div>{children}</div>;
}

ReactElement

ReactElement represents a React element, which is a lightweight description of what to render.

We would use ReactElement when you need to check if a variable is a React element specifically.

Example:

import React, { ReactElement } from 'react';

function isElement(element: any): element is ReactElement {
  return React.isValidElement(element);
}


const element = <div>Hello, world!</div>;
if (isElement(element)) {
  console.log('This is a React element.');
}

Summary

Use JSX.Element to specify the return type of a function component.

Use ReactNode to accept any renderable content as children in your components.

Use ReactElement when you need to check if a variable is a React element specifically.

In practice, you’ll often find yourself using JSX.Element to specify return types and ReactNode to handle children in your components.

ReactElement is less commonly used directly in application code but can be useful in certain utility functions or type guards.

Categories
React Answers

How to Show or hide element in React?

In React, you can show or hide elements by conditionally rendering them based on certain conditions using JavaScript expressions or state variables. Here are a few approaches you can use:

1. Conditional Rendering with JavaScript Expressions

We can conditionally render elements using JavaScript expressions within JSX.

For instance, we write

function MyComponent({ showElement }) {
  return (
    <div>
      {showElement && <p>This element will be shown if showElement is true.</p>}
    </div>
  );
}

Conditional Rendering with Ternary Operator

You can use a ternary operator for more complex conditions.

For instance, we write

function MyComponent({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? (
        <p>Welcome, User!</p>
      ) : (
        <p>Please log in to view this content.</p>
      )}
    </div>
  );
}

Conditional Rendering with State

We can control the visibility of elements using state.

import React, { useState } from 'react';

function MyComponent() {
  const [isVisible, setIsVisible] = useState(true);

  const toggleVisibility = () => {
    setIsVisible(!isVisible);
  };

  return (
    <div>
      <button onClick={toggleVisibility}>
        {isVisible ? 'Hide Element' : 'Show Element'}
      </button>
      {isVisible && <p>This element can be toggled.</p>}
    </div>
  );
}

Conditional Rendering with CSS

We can also use CSS to hide or show elements based on a class name or inline style.

function MyComponent({ isVisible }) {
  return (
    <div>
      <p className={isVisible ? 'visible' : 'hidden'}>Element with CSS</p>
    </div>
  );
}

Conditional Rendering with Libraries:

There are also libraries like react-visibility-sensor that help to conditionally render elements based on their visibility in the viewport.

import VisibilitySensor from 'react-visibility-sensor';

function MyComponent() {
  return (
    <VisibilitySensor>
      {({ isVisible }) => (
        <div>
          {isVisible ? <p>Element is visible</p> : <p>Element is not visible</p>}
        </div>
      )}
    </VisibilitySensor>
  );
}

Choose the approach that best fits your requirements and coding style. Each method has its advantages depending on the complexity of your application and the specific use case for showing or hiding elements.

Categories
React Answers

How to fix Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object in React?

The error message “Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object” typically occurs in React when we are trying to render a component but the element we are passing isn’t a valid React component.

Here are some common reasons for this error and how to fix them:

Check our import statements

Make sure we are importing the component correctly. For example, if we are using default exports, we should import it like this:

import MyComponent from './MyComponent';

And not like this:

import { MyComponent } from './MyComponent';

Check the component name

Ensure that we’ve correctly named our component when importing and rendering it. Typos can lead to React not recognizing the component.

Check the component definition

Make sure that the component we are trying to render is indeed a valid React component. Double-check the file where we define the component and ensure that it’s exporting correctly.

Check for circular dependencies

Circular dependencies can sometimes lead to this error. Make sure our component dependencies are set up correctly and there are no circular imports.

Check for default exports:

If we are using default exports, ensure that we are exporting the component correctly:

export default function MyComponent() {
    // component implementation
}

Check for typos or incorrect paths: Ensure that the file path to the component is correct. A wrong file path will result in React not finding the component.

Check if you’re passing an object instead of a component

Sometimes, this error occurs when you mistakenly pass an object instead of a component to the render() method. Make sure that the variable you’re passing is actually a React component.