Categories
React Answers

How to Get the Width of an Element in a React Component?

Sometimes, we want to get the width of an element in a React component.

In this article, we’ll look at how to get the width of an element in a React component.

Get the Width of an Element in a React Component

To get the width of an element in a React component, we can assign a ref to the element we want to get the width of.

Then we can use the offsetWidth property to get the width.

For instance, we can write:

import React, { useEffect, useRef } from "react";

export default function App() {
  const ref = useRef(null);

  useEffect(() => {
    console.log("width", ref.current.offsetWidth);
  }, []);

  return <div ref={ref}>Hello</div>;
}

to add the ref with the useRef hook.

Then we pass ref as the value of the ref prop to assign the ref to the div.

And then we get the width of the div with the offsetWidth property.

Conclusion

To get the width of an element in a React component, we can assign a ref to the element we want to get the width of.

Categories
React Answers

How to Set a Cookie in React?

Sometimes, we want to set cookies in our React apps.

In this article, we’ll look at how to to set cookies in our React apps.

Set a Cookie in React

To set cookies in our React apps, we can use the react-cookie library.

For instance, we can write:

import React, { useState } from "react";
import { useCookies } from "react-cookie";

export default function App() {
  const [cookies, setCookie] = useCookies(["name"]);
  const [name, setName] = useState("");

  const onChange = (newName) => {
    setCookie("name", newName, { path: "/" });
  };

  return (
    <div>
      <input
        value={name}
        onChange={(e) => {
          setName(e.target.value);
          onChange(e.target.value);
        }}
      />
      <h1>Hello {cookies?.name}!</h1>
    </div>
  );
}

We have input to changes the name state when we type in it.

It also calls onChange to change the value of the cookie with key name .

Then we get the cookie’s value with the cookie variable that we destructured from the useCookies hook.

The argument for useCookies is an array of keys of cookies to get.

Conclusion

To set cookies in our React apps, we can use the react-cookie library.

Categories
React Answers

How to Make React Components Draggable?

Sometimes, we want to create draggable components in our React app.

In this article, we’ll look at how to create draggable components in our React app.

Make React Components Draggable

To create draggable components in our React app, we can make a component that handles the mousemnove , mousedown , and mouseup events.

For instance, we can write:

import React, { useRef, useState, useEffect } from "react";

const style = {
  width: "200px",
  height: "200px",
  background: "#FF9900",
  color: "#FFFFFF",
  display: "flex",
  justifyContent: "center",
  alignItems: "center"
};

const DraggableComponent = () => {
  const [pressed, setPressed] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const ref = useRef();

  useEffect(() => {
    if (ref.current) {
      ref.current.style.transform = `translate(${position.x}px, ${position.y}px)`;
    }
  }, [position]);

  const onMouseMove = (event) => {
    if (pressed) {
      setPosition({
        x: position.x + event.movementX,
        y: position.y + event.movementY
      });
    }
  };

  return (
    <div
      ref={ref}
      style={style}
      onMouseMove={onMouseMove}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
    >
      <p>{pressed ? "Dragging..." : "Press to drag"}</p>
    </div>
  );
};

export default function App() {
  return (
    <div className="App">
      <DraggableComponent />
    </div>
  );
}

We have the style object with some styles for our draggable component.

Then we define the DraggableComponent which is a draggable component.

The pressed state tracks when the component is clicked.

position sets the div’s position.

In the useEffect callback, we set the transform CSS property to the position that’s dragged.

Next, we add the onMouseMove event handler to change the position of the div when the mouse is pressed.

This is used to handle the mousemove event.

To handle mouse down and mouse up, we set the pressed state with setPressed to true and false respectively so that the div can be moved when we press down the left mouse button.

Conclusion

To create draggable components in our React app, we can make a component that handles the mousemnove , mousedown , and mouseup events.

Categories
React Answers

How to Fix the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ Error?

Sometimes, we may encounter the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ error when we’re developing our React apps.

In this article, we’ll look at how the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ error when we’re developing our React apps.

Fix the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ Error

We can fix the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ error by rendering an array with the map method or render objects as strings or render the properties individually.

For instance, we can write:

const arr = [1, 2, 3];
export default function App() {
  return (
    <div className="App">
      {arr.map((num) => (
        <div key={num}>{num}</div>
      ))}
    </div>
  );
}

to render the arr array into multiple divs.

We set the key prop to a unique key.

And we render num , which is a number, as the content.

We can only render primitive values directly by putting them between curly braces.

If we have an object, we can render it as a string by writing:

const obj = { foo: 1, bar: 2 };
export default function App() {
  return <div className="App">{JSON.stringify(obj)}</div>;
}

We converted the obj object into a string with JSON.stringify .

Or we can render the properties in the object:

const obj = { foo: 1, bar: 2 };

export default function App() {
  return <div className="App">{obj.foo}</div>;
}

Conclusion

We can fix the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ error by rendering an array with the map method or render objects as strings or render the properties individually.

Categories
React Answers

How to Fix the Problem Where We Can’t Type in React Input Text Field?

Sometimes, we may run into the problem where we can’t type in a React input text field.

In this article, we’ll look at how to fix the problem where we can’t type in a React input text field.

Fix the Problem Where We Can’t Type in React Input Text Field

To fix the problem where we can’t type in a React input text field, we should add an onChange and value props to the input.

For instance, we can write:

import { useState } from "react";

export default function App() {
  const [searchString, setSearchString] = useState();
  return (
    <div className="App">
      <input
        type="text"
        value={searchString}
        onChange={(e) => setSearchString(e.target.value)}
      />
    </div>
  );
}

We defined the searchString state with the setSearchString state setter function with the useState hook.

Then we set the value prop’s value to searchString .

The onChange prop’s value is a function that takes the e.target.value , which is the inputted value, and call setSearchString with it as its argument.

Now we should be able to type into the text box since the input value is set as the value of a state and the state is used as the value of the value prop.

Conclusion

To fix the problem where we can’t type in a React input text field, we should add an onChange and value props to the input.