Categories
React Answers

How to Fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React?

Sometimes, we may run into the ‘A component is changing an uncontrolled input of type text to be controlled’ error when we’re developing React apps.

In this article, we’ll look at how to fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React.

Fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React

To fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React, we should make sure the value prop of the input is always set to a string.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [value, setValue] = useState();

  return (
    <div>
      <input
        name="name"
        value={value ?? ""}
        onChange={(e) => setValue(e.target.value)}
      />
    </div>
  );
}

to create the value state with the useState hook.

Its initial value is undefined.

Then in the input, we set the value prop to value ?? "" so that the value prop is set to an empty string when the value state is undefined or null.

Now we shouldn’t see this error in the console anymore.

Conclusion

To fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React, we should make sure the value prop of the input is always set to a string.

Categories
React Answers

How to Set Focus on an Input Field After Rendering with React?

Sometimes, we want to set focus on an input field after rendering with React.

In this article, we’ll look at how to set focus on an input field after rendering with React.

Set Focus on an Input Field After Rendering with React

To set focus on an input field after rendering with React, we can assign a ref to the input element with the useRef hook.

Then we call focus on the current value of the ref to focus on the input.

For instance, we write:

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

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

  useEffect(() => {
    inputReference.current.focus();
  }, []);

  return (
    <div>
      <input ref={inputReference} />
    </div>
  );
}

to call useRef to create a ref and assign it to inputReference.

Then we call inputReference.current.focus() in the useEffect callback to focus on the input.

inputReference.current will be set to the input element when we set inputReference as the value of the ref prop of the input.

We pass in an empty array as the 2nd argument so that the useEffect callback only runs when the component mounts.

Finally, we assign the inputReference ref to the input by setting it as the value of the ref prop.

Conclusion

To set focus on an input field after rendering with React, we can assign a ref to the input element with the useRef hook.

Then we call focus on the current value of the ref to focus on the input.

Categories
React Answers

How to Conditionally Add Attributes to React Components?

Sometimes, we want to conditionally add attributes to React components.

In this article, we’ll look at how to conditionally add attributes to React components.

Conditionally Add Attributes to React Components

To conditionally add attributes to React components, we can set attributes to any JavaScript expression we want.

For instance, we write:

import React from "react";

export default function App() {
  const required = true;
  const disabled = false;

  return <input type="text" disabled={disabled} required={required} />;
}

to set required to true and disabled to false.

Then the following will be rendered as a result:

<input type="text" required>

Conclusion

To conditionally add attributes to React components, we can set attributes to any JavaScript expression we want.

Categories
React Answers

How to Pass Props to Nested Child Components in React?

Sometimes, we want to pass props to nested child components in React.

In this article, we’ll look at how to pass props to nested child components in React.

Pass Props to Nested Child Components in React

To pass props to nested child components in React, we can use the React.Children.map and the React.cloneElement methods to pass props to child components.

For instance, we write:

import React from "react";

const Child = ({ doSomething, value }) => (
  <button onClick={() => doSomething(value)}>Click Me</button>
);

const Parent = ({ children }) => {
  function doSomething(value) {
    console.log("do something: ", value);
  }

  const childrenWithProps = React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { doSomething });
    }
    return child;
  });

  return <div>{childrenWithProps}</div>;
};

export default function App() {
  return (
    <Parent>
      <Child value={1} />
      <Child value={2} />
    </Parent>
  );
}

We create the Child component that takes a few props and renders a button which runs doSomething when we click on it.

Then we create the Parent component that takes the children prop.

We pass the props into the children components by calling React.Children.map method with children and a callback that takes the child parameter.

And then we check if child is a valid component with React.isValidElement.

And if it is, then we return the element with the props passed into it with:

React.cloneElement(child, { doSomething })

Otherwise, we return child as is.

Then we returned child components with the props passed in are assigned to childrenWithProps.

And finally, they’re rendered in the div.

In App, we add the Parent component with the Child components inside it.

Therefore, when we click each button, we see the value prop value passed into it logged.

Conclusion

To pass props to nested child components in React, we can use the React.Children.map and the React.cloneElement methods to pass props to child components.

Categories
JavaScript Answers

How to Play a Beep Sound on Button Click with JavaScript?

Sometimes, we want to play a beep sound on button click with JavaScript.

In this article, we’ll look at how to play a beep sound on button click with JavaScript.

Play a Beep Sound on Button Click with JavaScript

To play a beep sound on button click with JavaScript, we can add an event listener to a button.

And in the event listener, we can call the play method on the Audio instance with the URL set to the beep sound clip.

For instance, we write:

<button>
  foo
</button>

to add a button.

Then we write:

const audio = new Audio('https://www.soundjay.com/buttons/beep-01a.mp3')
const button = document.querySelector('button')

button.addEventListener('click', (e) => {
  audio.play()
})

to create an Audio instance with the beep sound URL and assign it to audio.

Then we select the button with document.querySelector.

And finally, we call button.addEventListener with 'click' to add a click event listener.

The 2nd argument is a callback that runs when we click the button.

In it, we call audio.play to play the clip.

Therefore, when we click the button, the beep sound clip will play.

Conclusion

To play a beep sound on button click with JavaScript, we can add an event listener to a button.

And in the event listener, we can call the play method on the Audio instance with the URL set to the beep sound clip.