Categories
React Answers

How to Create a React Modal that Appends to the body Element?

Sometimes, we want to create a React modal that appends to the body element.

In this article, we’ll look at how to create a React modal that appends to the body element.

Create a React Modal that Appends to the body Element

To create a React modal that appends to the body element, we can use the react-portal package.

To install it, we run:

npm i react-portal

Then we write:

import { PortalWithState } from "react-portal";

export default function App() {
  return (
    <div>
      <PortalWithState closeOnOutsideClick closeOnEsc>
        {({ openPortal, closePortal, portal }) => (
          <>
            <button onClick={openPortal}>Open Portal</button>
            {portal(
              <p>
                hello world <button onClick={closePortal}>Close me!</button>,
              </p>
            )}
          </>
        )}
      </PortalWithState>
    </div>
  );
}

to add a modal with the PortalWithState component.

The closeOnOutsideClick prop lets us close the modal when we click outside it.

And the closeOnEsc prop lets us close the modal when we press the Esc key.

In the render prop function, we have the modal content in the argument of the portal function

The openPortal function lets us open the modal.

And the closePortal function closes the modal.

Conclusion

To create a React modal that appends to the body element, we can use the react-portal package.

Categories
React Answers

How to Animate List Reordering with React?

Sometimes, we want to animate list reordering with React

In this article, we’ll look at how to animate list reordering with React

Animate List Reordering with React

To animate list reordering with React, we can use the react-flip-move package.

To install it, we run:

npm i react-flip-move

Then we add the FlipMove component and wrap it around the array of items we want to animate when reordering by writing:

import { shuffle } from "lodash";
import { forwardRef, useState } from "react";
import FlipMove from "react-flip-move";

const Num = forwardRef(({ number }, ref) => <div ref={ref}>{number}</div>);

export default function App() {
  const [nums, setNums] = useState([1, 2, 3, 4, 5]);

  return (
    <div>
      <button onClick={() => setNums((nums) => shuffle(nums))}>shuffle</button>
      <FlipMove>
        {nums.map((n) => (
          <Num key={n} number={n} />
        ))}
      </FlipMove>
    </div>
  );
}

We have the Num component with a ref passed from App with forwardRef .

And we assign the ref to the div.

Next, in App , we create the nums state with an array of items.

Then we add a shuffle button that shuffle nums with the Lodash shuffle function.

Finally, we put the array we want to animate when we shuffle it in the FlipMove component.

Now when we click shuffle, we should see the animation generated with the react-filp-move package.

Conclusion

To animate list reordering with React, we can use the react-flip-move package.

Categories
React Answers

How to Modify Text Area Values with React?

Sometimes, we want to modify the value of the text area with React.

In this article, we’ll look at how to modify the value of the text area with React.

Modify Textarea Values with React

To modify the value of the text area with React, we set the onChange prop to a function that calls a state setter function with e.target.value .

For instance, we can write:

import { useState } from "react";

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

  return (
    <div>
      <textarea value={val} onChange={(e) => setVal(e.target.value)}></textarea>
    </div>
  );
}

We create the val state with the useState hook.

Then we add a textarea element that has the onChange prop set to a function that calls setValue with e.target.value to set the val state to the input value of the textarea .

Finally, we set the value prop to val to update the display of the textarea with the inputted value.

Conclusion

To modify the value of the text area with React, we set the onChange prop to a function that calls a state setter function with e.target.value .

Categories
React Answers

How to Initiate a Draft.js Editor with Content within a React App?

Sometimes, we want to initiate a Draft.js editor with content within a React app.

In this article, we’ll look at how to initiate a Draft.js editor with content within a React app.

Initiate a Draft.js Editor with Content within a React App

To initiate a Draft.js editor with content within a React app, we can use the ContentState.createFromText method to create the initial content for the text editor.

Then we can pass that into the EditorState.createWithContent method to set the content state as the editor’s initial content.

For instance, we can write:

import { ContentState, Editor, EditorState } from "draft-js";
import { useRef, useState } from "react";

const content = ContentState.createFromText("<b>hello world</b>");

export default function App() {
  const [editorState, setEditorState] = useState(() =>
    EditorState.createWithContent(content)
  );

  const editor = useRef(null);
  const focusEditor = () => {
    editor.current.focus();
  };

  return (
    <div
      style={{ border: "1px solid black", minHeight: "6em", cursor: "text" }}
      onClick={focusEditor}
    >
      <Editor
        ref={editor}
        editorState={editorState}
        onChange={setEditorState}
        placeholder="Write something!"
      />
    </div>
  );
}

We add:

const content = ContentState.createFromText("<b>hello world</b>");

to set “<b>hello world</b>” to create the initial content of the editor,

Then we have:

const [editorState, setEditorState] = useState(() =>
  EditorState.createWithContent(content)
);

to set the content as the initial state of the editorState , which has the initial value of the text editor which can be used by Draft.js’ Editor component.

Then we set the editorState prop to the editorState state as its value.

The onChange prop is set to the setEditorState function that sets binds the editorState to the input value of the editor.

Therefore, <b>hello world</b> is the content of the editor when it’s loaded initially.

Conclusion

To initiate a Draft.js editor with content within a React app, we can use the ContentState.createFromText method to create the initial content for the text editor.

Then we can pass that into the EditorState.createWithContent method to set the content state as the editor’s initial content.

Categories
React Answers

How to Fix a Checkbox not Emitting the Change Event in React?

Sometimes, we may encounter the issue where a checkbox not emitting the change event when we’re developing a React app.

In this article, we’ll look at how to fix the issue where a checkbox not emitting the change event when we’re developing a React app.

Fix a Checkbox not Emitting the Change Event in React

To fix the issue where a checkbox not emitting the change event when we’re developing a React app, we should get the checked value of the checkbox by setting the onChange prop to a function that gets the checked value of the checkbox.

Then we can set the checkbox value by setting the checkbox to a state that’s set to the checked value of the checkbox.

For instance, we can write:

import { useState } from "react";

export default function App() {
  const [active, setActive] = useState(false);
  return (
    <div className="App">
      <input
        type="checkbox"
        checked={active}
        onChange={(e) => setActive(e.target.checked)}
      />
    </div>
  );
}

to set the onChange prop to a function that calls the setActive function with e.target.checked to set the active state to the checked value of the checkbox.

Then we set the checked prop to the value of the active state to make the checkbox update with the checked value of the active state.

Conclusion

To fix the issue where a checkbox not emitting the change event when we’re developing a React app, we should get the checked value of the checkbox by setting the onChange prop to a function that gets the checked value of the checkbox.

Then we can set the checkbox value by setting the checkbox to a state that’s set to the checked value of the checkbox.