Categories
React Tips

React Tips — React and Redux, Navigation, Drop Down Values

Spread the love

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

Setting State When a Drop Down Value is Changed

We can set the selected value from the dropdown as a state value by setting the key dynamically and the value to the event.target.value .

For instance, we can write:

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = { fruit: '' };
  }

  handleChange = (event) => {
    this.setState({ [event.target.name]: event.target.value });
  }

  render() {
    return (
      <select value={this,state.fruit} name='fruit' `handleChange={this.handleChange}`>
        <option value="apple">Apple</option>
        <option value="banana">Banana</option>
        <option value="cranberry">Cranberry</option>
      </select>
    )
  }

}

We set the fruit state to the selected value with the handleChange method.

It just calls setState to set the fruit state with the value, which is stored in event.target.value .

Update Nested State Properties in React

We can set nested state properties with setState .

It takes a callback with the previous state, then we return an object with the new state.

For instance, we can write:

this.setState(state=> ({ ...this.state.someProp, flag: false} }));

Or we can write:

this.setState({ someProperty: { ...this.state.someProperty, flag: false} });

to update the state without the callback.

In either example, we merge the new value to the old object with the spread operator.

Get First N Number of Elements from an Array

We can get the first N number of elements from an array with the slice method.

For instance, we can write:

const size = 5;
const items = list.slice(0, size).map(i => {
  return <Foo item={i} key={i.id} />
}

return (
  <div>
    {items}
  </div>
)

inside the render method or the function component.

We get the first 5 items with the slice method.

Then we use map to return the list of items to render.

And then we can put that anywhere.

Push to History in React Router

We can use the this.props.history.push method of React Router if we use it with a class component.

For instance, we can write:

import React from "react";
import { withRouter } from "react-router-dom";

class Foo extends React.Component {
  //...
  go() {
    this.props.history.push("/some/path");
  }
  //...
}
export default withRouter(Foo);

We have the go method inside our React component to call this.prop.history.push with the path we want to go to.

It’s available because we called the withRouter higher-order component to add the method.

With the hooks version of React Router, we can write:

import { useHistory } from "react-router-dom";

function App() {
  const history = useHistory();

  const goHome = () => {
    history.push("/home");
  }

  return (
    <button type="button" onClick={goHome}>
      Go home
    </button>
  );
}

We use the useHistory hook to get the history object and we call push on it to go to the path we want.

React Redux mapDispatchToProps

With React Redux, we use the mapDispatchToProps method to map dispatch actions to props.

For instance, we can write:

class App extends Component {
  sendAlert(){
    this.props.sendAlert()
  }

  render() {
    <div>
      <h1>alert: {this.props.alert}</h1>
      <Button onClick={sendAlert}/>
    </div>
  }
}

function mapDispatchToProps(dispatch) {
  return({
    sendAlert: () => {dispatch(ALERT_ACTION)}
  })
}

function mapStateToProps(state) {
  return { alert: state.alert }
}

export const FancyButtonContainer = connect(
  mapStateToProps, mapDispatchToProps)(
  App
)

We have the this.propss.sendAlert method, which is the one that’s returned with nmapDispatchToProps .

mapDispatchToProps is a function that we can use with the connect higher-order component to map the dispatch action to props.

Likewise, mapStateToProps lets us return the state from the Redux store and make it available as a prop in our component.

So this.props.alert is the value of the alert property in the returned object.

Update the Parent’s State

We can update the parent;’s state by passing in a function from the parent to the child as a prop.

Then in the child component, we can call it to update the state.

For instance, we can write:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.handler = this.handler.bind(this);
  }

  handler() {
    this.setState({
      foo: 'bar'
    })
  }

  render() {
    return <Child handler = {this.handler} />
  }
}

class Child extends React.Component {
  render() {
    return <button onClick={this.props.handler}>click me</button>
  }
}

We pass the this.handler method to the Child component.

We’ve to remember to call bind with this on it so the value of this will be the parent.

Then we can call it in the Child by passing it into the onClick prop as this.props.handler .

Conclusion

We can pass functions from the parent component to the child.

We can set the state when the dropdown is changed.

There are a few ways to navigate with React Router.

Redux can be used to map actions and states to props of a component.

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 *