Categories
React Tips

React Tips — Redux States, Dynamic Elements, and Pretty Print JSON

Spread the love

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Access Store State in React Redux

We can access store state in React Redux with the mapStateProps method.

For instance, we can write:

import React from "react";
import { connect } from "react-redux";

const App = (props) => {
  return (
    <div>
      <h1>{props.name}</h1>
    </div>
  );
}

const mapStateToProps = state => {
  return {
    name: state.name
  };
};
export default connect(mapStateToProps)(App);

We call connect with mapStateToProps to add the Redux store states as props of the App component.

Then we can just get it with props.name as we did in App .

Render Repeating React Elements

We can render repeating React elements with the map method.

For instance, we can write:

{this.props.titles.map(title =>
  <div key={title}>{title}</div>
)}

We have the titles prop and call map to return a div from each title entry.

We cal also use the Array.from method to make an array from something that’s not an array.

For instance, we can write:

<div>
  { Array.from({ length: 3 }, (value, index) => <div key={value.id}>}{value.name}</div>) }
</div>

We called Array.from create an empty array with length of 3, then we map the empty slots to an element.

There’s also the Array.fill method to render the elements from empty array slots:

<div>
 { Array(3).fill(<div />) }
</div>

Toggle Class when Clicked in a React Component

We can set a state to let us toggle a class when we click something in a React component.

For instance, we can write:

class App extends Component {
  constructor(props) {
    super(props);
    this.addActiveClass = this.addActiveClass.bind(this);
    this.state = {
      active: false,
    };
  }

  toggleClass() {
    const currentState = this.state.active;
    this.setState({ active: !currentState });
  };

  render() {
    return (
      <div
        className={this.state.active ? 'active': null}
        onClick={this.toggleClass}
      >
        <p>hello</p>
      </div>
    )
  }
}

We have the toggleClass method which is called when we click on the div.

In the method, we set the active state to the opposite of the current value.

Then we get the class name depending of the value of this.state.active .

Dynamically Add Child Components in React

To dynamically add child components to React, we can change the state, and then we can render what we want based on the state.

For instance, we can write:

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      data: [
        { id: 1, name: "foo" }
      ]
    }
    this.addChild = this.addChild.bind(this);
  }

  addChild() {
    const newData = { id: 2, name: "bar" };
    this.setState(state => [...state.data, newData])
  }

  render() {
    return (
      <div>
         <button onClick={this.addChild}>Add name</button>
         {this.state.data.map((item) => (
            <div key={item.id}>{item.name></div>
         )}
      </div>
    );
  }
}

We have the addChild method which calls setState to set the new value of data by passing in a callback to append the new entry to the data state.

Then in the render method, we map the data state to an entry in by calling array instance’s map method.

We return a component or element we want to display.

Pretty Printing JSON with React

We can pretty print JSON with React with the pre element.

For instance, we can write:

class PrettyPrintJson extends React.Component {
  render() {
    const { data }= this.props;
    return (<div><pre>{JSON.stringify(data, null, 2) }</pre></div>);
  }
}

We called JSON.stringify with 2 as the 3rd argument to indent the data that we display as the data.

With a function component, we can write:

const PrettyPrintJson = ({data}) => (
  <div>
    <pre>
      {JSON.stringify(data, null, 2)}
    </pre>
  </div>
);

We just return the JSX expression for pretty print directly.

Also, we can cache the JSON data with React.memo .

For example, we can write:

const PrettyPrintJson = React.memo(
  {data}) => (
    <div>
      <pre>
        {JSON.stringify(data, null, 2)}
      </pre>
    </div>
  )
);

Conclusion

We can render repeated elements by using array methods to map data to JSX expressions.

Also, we can pretty-print JSON by using JSON.stringify to pretty print our JSON with indentation.

We can toggle classes and render elements dynamically by changing states and then rendering whatever we want with the render method.

Finally, we can use mapStateToProps to map Redux states to props.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *