Categories
React Answers

How to create a number input with no negative, decimal, or zero value values with React?

Sometimes, we want to create a number input with no negative, decimal, or zero value values with React.

In this article, we’ll look at how to create a number input with no negative, decimal, or zero value values with React.

How to create a number input with no negative, decimal, or zero value values with React?

To create a number input with no negative, decimal, or zero value values with React, we can create our own input component.

For instance, we write:

import React, { useState } from "react";

const PositiveInput = () => {
  const [value, setValue] = useState("");

  const onChange = (e) => {
    const value = e.target.value.replace(/[^\d]/, "");

    if (+value !== 0) {
      setValue(value);
    }
  };

  return <input type="text" value={value} onChange={onChange} />;
};

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

We create the PositiveInput component that lets us only enter positive numbers.

In the component, we have the value state.

And we define the onChange function that sets the value state by getting the value from the input.

And we replace all the non numerical values in the input value with empty strings.

This is done with const value = e.target.value.replace(/[^\d]/, "");.

Then if value isn’t 0, then we call setValue to set value.

Next, we set the value prop of the input to value and the onChange prop to onChange.

Finally, we add the input to App.

Conclusion

To create a number input with no negative, decimal, or zero value values with React, we can create our own input component.

Categories
React Answers

How to fix the newlines character ignored by JSX tables issue with React?

Sometimes, we want to fix the newlines character ignored by JSX tables issue with React.

In this article, we’ll look at how to fix the newlines character ignored by JSX tables issue with React.

How to fix the newlines character ignored by JSX tables issue with React?

To fix the newlines character ignored by JSX tables issue with React, we can set the white-space CSS property to pre in the cell.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <>
      <style>
        {`.pre-wrap {
          white-space: pre-wrap
        }`}
      </style>
      <table>
        <tbody>
          <tr>
            <td className="pre-wrap">
              {
                "Line 1\nLine 2\nLine 3\nThis is a cell with white-space: pre-wrap"
              }
            </td>
          </tr>
        </tbody>
      </table>
    </>
  );
}

We have a string that have some new line characters between a few substrings.

To make them display in separate lines, we add the pre-wrap class which sets the white-space CSS property to pre-wrap.

And we set the className of the td to pre-wrap to apply the styles.

Now we should see that each line in the string are displayed on separate lines.

Conclusion

To fix the newlines character ignored by JSX tables issue with React, we can set the white-space CSS property to pre in the cell.

Categories
React Answers

How to listen for mouse wheel events in React?

Sometimes, we want to listen for mouse wheel events in React.

In this article, we’ll look at how to listen for mouse wheel events in React.

How to listen for mouse wheel events in React?

To listen for mouse wheel events in React, we can set the onWheel prop to the mouse wheel event listener.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <>
      <div style={{ height: 600, width: 300 }} onWheel={(e) => console.log(e)}>
        hello world
      </div>
    </>
  );
}

We set onWheel to a function that logs the event object.

Now when we scroll up and down with the mouse wheel, we should see the event object logged.

Conclusion

To listen for mouse wheel events in React, we can set the onWheel prop to the mouse wheel event listener.

Categories
React Answers

How to update an object in a React component state?

Sometimes, we want to update an object in a React component state.

In this article, we’ll look at how to update an object in a React component state.

How to update an object in a React component state?

To update an object in a React component state, we can manipulate the state object with object spread.

For instance, we write:

import React, { useState } from "react";

const u = {
  1: { id: 1, name: "John" },
  2: { id: 2, name: "Jim" },
  3: { id: 3, name: "James" }
};
export default function App() {
  const [users, setUsers] = useState(u);

  const addUser = () => {
    setUsers((u) => {
      return {
        ...u,
        [Object.keys(u).length + 1]: {
          id: Object.keys(u).length + 1,
          name: "Mary"
        }
      };
    });
  };

  return (
    <>
      <button onClick={addUser}>add user</button>
      {Object.entries(users).map(([, val]) => {
        const { id, name } = val;
        return <p key={id}>{name}</p>;
      })}
    </>
  );
}

We have the u object with some user data.

And we set u as the initial value of the users state.

Then we define the addUser function that calls setUsers with a function that returns an object with the new user entry with the key set to Object.keys(u).length + 1.

Object.keys(u) returns an array of object keys.

Then we set addUser as the value of the onClick prop of the button.

Finally, we render the entries in users with:

Object.entries(users).map(([, val]) => {
  const { id, name } = val;
  return <p key={id}>{name}</p>;
})

Now when we click add user, we see new entries displayed.

Conclusion

To update an object in a React component state, we can manipulate the state object with object spread.

Categories
React Answers

How to play local video with React’s react-player library?

Sometimes, we want to play local video with React’s react-player library.

In this article, we’ll look at how to play local video with React’s react-player library.

How to play local video with React’s react-player library?

To play local video with React’s react-player library, we can add a file input that accepts a file.

Then we can convert the file object obtained to a file path that can be used with react-player.

For instance, we write:

import React, { useState } from "react";
import ReactPlayer from "react-player";

export default function App() {
  const [videoFilePath, setVideoFilePath] = useState(null);

  const handleVideoUpload = (event) => {
    const [file] = event.target.files;
    setVideoFilePath(URL.createObjectURL(file));
  };

  return (
    <>
      <input type="file" onChange={handleVideoUpload} />
      <ReactPlayer url={videoFilePath} width="100%" height="100%" controls />
    </>
  );
}

We define the videoFilePath state with useState.

Then we define the handleVideoUpload function that gets the file from the e.target.files object.

Next, we convert file to a video path that can be used with reacy-player with URL.createObjectURL.

Then we set url to videoFilePath.

Now when we select a video file from the file input, then we’ll see the video file displayed.

Conclusion

To play local video with React’s react-player library, we can add a file input that accepts a file.

Then we can convert the file object obtained to a file path that can be used with react-player.