Categories
React Answers

How to display binary data as image in React?

Sometimes, we want to display binary data as image in React.

In this article, we’ll look at how to display binary data as image in React.

How to display binary data as image in React?

To display binary data as image in React, we can set the src prop of the img element to a base64 URL.

For instance, we write

const data =
  "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";

const Example = ({ data }) => <img src={`data:image/jpeg;base64,${data}`} />;

to set the src prop of the img element in Example to a base64 URL with the binary image data.

Then the image will be displayed.

Conclusion

To display binary data as image in React, we can set the src prop of the img element to a base64 URL.

Categories
React Answers

How to only allow numbers in a number input in React?

Sometimes, we want to only allow numbers in a number input in React.

In this article, we’ll look at how to only allow numbers in a number input in React.

How to only allow numbers in a number input in React?

To only allow numbers in a number input in React, we can check for the key that’s pressed.

For instance, we write

<input
  onKeyPress={(event) => {
    if (!/[0-9]/.test(event.key)) {
      event.preventDefault();
    }
  }}
/>

to set the onKeyPress prop to a function that checks the key that’s pressed with event.key.

If it’s not 0 to 9, then we call preventDefault to stop the character from being appending to the input value.

Conclusion

To only allow numbers in a number input in React, we can check for the key that’s pressed.

Categories
React Answers

How to fix Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks?

To fix Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks, we should put hook calls at the top level of a component.

For instance, we write

const { useState } = React;

function App() {
  const [name, setName] = useState("Mary");
  const [age, setAge] = useState(16);
  const [license, setLicense] = useState("A123456");

  return (
    <div>
      Name:{" "}
      <input
        value={name}
        onChange={(e) => {
          setName(e.target.value);
        }}
      />
      <br />
      Age:{" "}
      <input
        value={age}
        type="number"
        onChange={(e) => {
          setAge(+e.target.value);
        }}
      />
      {age >= 16 && (
        <span>
          <br />
          Driver License:
          <input
            value={license}
            onChange={(e) => {
              setLicense(e.target.value);
            }}
          />
        </span>
      )}
    </div>
  );
}

to call useState at the top of the App component only.

Then React can call all the hooks in order.

We should not nest any hooks in our component.

Otherwise, we’ll get this error.

Categories
React Answers

How to fix React form setState is one step behind onChange?

Sometimes, we want to fix React form setState is one step behind onChange

In this article, we’ll look at how to fix React form setState is one step behind onChange.

How to fix React form setState is one step behind onChange?

To fix React form setState is one step behind onChange, we call setState with an object with the states we want to change and a function that’s called after the states are changed.

For instance, we write

class Comp extends Component {
  //...
  handleChange = (e) => {
    console.log(e.target.value);
    this.setState({ message: e.target.value }, this.handleSubmit);
  };
  //...
}

to call setState with { message: e.target.value } to set the message state to e.target.value.

After the states are set then this.handleSubmit is called.

Conclusion

To fix React form setState is one step behind onChange, we call setState with an object with the states we want to change and a function that’s called after the states are changed.

Categories
React Answers

How to make API call with hooks in React?

Sometimes, we want to make API call with hooks in React.

In this article, we’ll look at how to make API call with hooks in React.

How to make API call with hooks in React?

To make API call with hooks in React, we can do it in the useEffect callback.

For instance, we write

const Todo = () => {
  const [todo, setTodo] = React.useState(null);
  const [id, setId] = React.useState(1);

  const getTodo = async (id) => {
    const results = await fetch(
      `https://jsonplaceholder.typicode.com/todos/${id}`
    );
    const data = await results.json();
    setTodo(data);
  };

  React.useEffect(() => {
    if (id === null || id === "") {
      return;
    }
    getTodo(id);
  }, [id]);

  return (
    <div>
      <input value={id} onChange={(e) => setId(e.target.value)} />
      <br />
      <pre>{JSON.stringify(todo, null, 2)}</pre>
    </div>
  );
};

to define the getTodo which makes a get request to an endpoint to get some data.

We get the response data from the json method.

Then we call useEffect with a callback that calls getTodo with id.

The 2nd argument is [id] so the useEffect callback will be called when id changes.

Conclusion

To make API call with hooks in React, we can do it in the useEffect callback.