Categories
React Answers

How to style an Alert element in React Native?

To style an Alert element in React Native, we set the Modal‘s style prop.

For instance, we write

<Modal style={{ background: "red" }} ref={"modal1"}>
  <Text style={{ color: "white" }}>Basic modal</Text>
  <Button onPress={this.toggleSwipeToClose} style={styles.btn}>
    Disable swipeToClose({this.state.swipeToClose ? "true" : "false"})
  </Button>
</Modal>

to set the style prop of the Modal to { background: "red" } to make the background red.

And we set the Text style by setting the Text‘s style prop to { color: "white" }.

And we set the Button‘s style to styles.btn

Categories
React Answers

How to trigger a Redux action from outside a component with React?

To trigger a Redux action from outside a component with React, we call store.dispatch from anywhere in our project.

For instance, we write

import { store } from "/path/to/createdStore";

function testAction(text) {
  return {
    type: "TEST_ACTION",
    text,
  };
}

store.dispatch(testAction("StackOverflow"));

to call the testAction function to return the action type and text value.

And then we call store.dispatch to with the object returned by testAction to dispatch the TEST_ACTION action.

Categories
React Answers

How to mock localStorage methods with Jest?

To mock localStorage methods with Jest, we call jest.spyOn.

For instance, we write

jest.spyOn(window.localStorage.__proto__, "setItem");

to call jest.spyOn with window.localStorage.__proto__, which is the local storage prototype.

We mock the localStorage.setItem method by calling spyOn with 'setItem' as the 2nd argument.

Categories
React Answers

How to render nested array elements in React?

To render nested array elements in React, we can use the JavaScript array map method.

For instance, we write

list.map((item, index) => {
  return (
    <div key={index}>
      <ul>{item.value}</ul>
      {item.list.map((subitem, i) => {
        return (
          <ul>
            <li>{subitem.value}</li>
          </ul>
        );
      })}
    </div>
  );
});

to call map on list and item.list to render the values in them.

We call map with a function to render the elements we want in list and item.list.

Categories
React Answers

How to avoid HTML escaping of text children when calling React.createElement?

To avoid HTML escaping of text children when calling React.createElement, we use the dangerouslySetInnerHTML prop.

For instance, we write

const Component = () => (
  <span dangerouslySetInnerHTML={{ __html: "&gt;&lt;" }} />
);

ReactDOM.render(<Component />, document.getElementById("container"));

to create the Component component that renders the "&gt;&lt;" as raw HTML by setting it as the value of __html in the object that we set as the value of the dangerouslySetInnerHTML prop.