Categories
React Answers

How to use useref hook in React?

To use the useRef hook in React, we call it in our component to return a ref.

Then we can assign that to an element.

For instance, we write

function TextInputWithFocusButton() {
  const inputEl = useRef(null);

  const onButtonClick = () => {
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

to set the input’s ref prop to the inputEl ref which we created with useRef.

Then we can access the input with inputEl.current.

And we call focus on it to focus on the input.

Categories
React Native Answers

How to override style with React Native?

To override style with React Native, we set the style prop to the styles we want by putting them in an object.

For example, we write

const styles = StyleSheet.create({
  CircleShapeView: {
    width: 50,
    height: 50,
    borderRadius: 50 / 2,
    backgroundColor: "#000",
  },
});

//...

<Image style={[styles.CircleShapeView, { backgroundColor: "#fff" }]} />;

to set the style prop of the image to an array with the styles object and an object with the backgroundColor we want to set.

The background color is #fff since the 2nd object has the latest backgroundColor value.

Categories
React Answers

How to fix ‘Switch’ is not exported from ‘react-router-dom’ with React Router?

To fix ‘Switch’ is not exported from ‘react-router-dom’ with React Router, we should use version 5 of React Router.

First we uninstall the existing version of React Router with

npm uninstall react-router-dom

Then install the version 5.2.0 of react-router-dom

npm install react-router-dom@5.2.0
Categories
React Native Answers

How to set the modal background with React Native?

To add a modal background with React Native, we add the Modal component.

For instance, we write

<Modal
   theme={{
     colors: {
       backdrop: 'transparent',
     },
   }}
  {...otherProps}
>
 {children}
</Modal>

to add the Modal component with the children prop as its content.

We set the backdrop color by setting the colors.backdrop property in theme.

Categories
React Native Answers

How to set status bar color with React Native?

To set status bar color with React Native, we call the StatusBar.setBarStyle and StatusBar.setBackgroundColor methods.

For instance, we write

import {StatusBar} from 'react-native';

class Comp extends Component {
  //...
  componentDidMount() {
    StatusBar.setBarStyle("light-content", true);
    StatusBar.setBackgroundColor("#0996AE");
  }
  //...
}

to call StatusBar.setBarStyle to set the light-content option to true to make the content color light.

And we call StatusBar.setBackgroundColor to set the background color.