Categories
React Answers

How to Use Local Storage with React?

Sometimes, we want to store data on local storage in our React app.

In this article, we’ll look at how tostore data on local storage in our React app.

Use Local Storage with React

We can use the native local storage methods in React.

For instance, we can write:

import React from 'react'

class App extends React.Component {
  constructor(props) {
    super(props);
    const storedClicks = 0;

    if (localStorage.getItem('clicks')) {
      storedClicks = +(localStorage.getItem('clicks'));
    }

    this.state = {
      clicks: storedClicks
    };
    this.click = this.click.bind(this);
  }

  onClick() {
    const newClicks = this.state.clicks + 1;
    this.setState({ clicks: newClicks });
    localStorage.setItem('clicks', newClicks);
  }

  render() {
    return (
      <div>
        <button onClick={this.onClick}>Click me</button>
        <p>{this.state.clicks} clicks</p>
      </div>
    );
  }
}

We get the clicks from local storage if it exists.

Then we parse it if it exists and set that as the initial value of the clicks state.

Then in the render method, we have a button to update the clicks state and the local storage clicks value with the onClick method.

It updates the clicks state.

Also, we update the local storage’s clicks value after that.

Conclusion

We can use the native local storage methods in React.

Categories
React Answers

Hoe to Update the Context Value in Provider from the Consumer?

Sometimes, we want to update the context value in a provider from the consumer of the React Context API.

In this article, we’ll look at how to to update the context value in a provider from the consumer of the React Context API.

Update the Context Value in Provider from the Consumer

We can update the context value from the provider if we pass in the function into the context.

For instance, we can write:

const MyContext = React.createContext({});

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: ""
    };
  }

  onChange(e){
    const name = e.target.value;
    this.setState({
      name
    });
    this.props.context.updateValue('name', name);
  }

  render() {
    return (
       <React.Fragment>
         <input onChange={this.onChange} />
       </React.Fragment>
    )
  }
}

const withContext = (Component) => {
  return (props) => {
    <MyContext.Consumer>
      {(context) => {
           return <Component {...props} context={context} />
      }}
    </MyContext.Consumer>
  }
}

Child = withContext(Child)

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "bar",
    };
  }

  updateValue = (key, val) => {
    this.setState({[key]: val});
  }

  render() {
    return (
      <MyContext.Provider value={{ state: this.state, updateValue: this.updateValue }}>
        <Child />
      </MyContext.Provider>
    )
  }
}

We create the context and pass the value from the Parent to the components in the context.

The object has the state and the updateValue function.

We then get the updateValue method from the props.context property, which is what we have.

Then we set the name by calling the updateValue method to set the name state of the Parent .

We’ve to remember to add the MyContext.Consumer to whatever component is consuming the context.

To do that, we created the withContext higher-order component to wrap any component with the context consumer.

Conclusion

We can update the context value from the provider if we pass in the function into the context.

Categories
React Answers

How to Edit the Values of Input Controlled Components in React?

Sometimes, we want to edit the input values of controlled input components in a React component.

In this article, we’ll look at how to edit the value of value controlled input components in a React component.

Edit the Values of Input Controlled Components in React

We can edit the input values of multiple controlled input components by providing their own change handlers.

For instance, we can write:

class Form extends React.Component {
  constructor() {
    this.state = {};
  }

  changeFirstName(event) {
    const contact = this.state.contact;
    contact.firstName = event.target.value;
    this.setState({ contact });
  }

  changeLastName(event) {
    const contact = this.state.contact;
    contact.lastName = event.target.value;
    this.setState({ contact });
  }

  changePhone(event) {
    const contact = this.state.contact;
    contact.phone = event.target.value;
    this.setState({ contact });
  }

  render() {
    return (
      <div>
        <input type="text" onChange={this.changeFirstName.bind(this)} value={this.state.contact.firstName}/>
        <input type="text" onChange={this.changeLastName.bind(this)} value={this.state.contact.lastName}/>
        <input type="text" onChange={this.changePhone.bind(this)} value={this.state.contact.phone}/>
      </div>
    );
  }
}

We have 3 inputs, one for the first name, one for the last name, and one for the phone number.

Then in each handler, we get the values with event.target.value and then assign it to the state.

Each handler is passed into the onChange prop of each input.

We’ve to call bind(this) to return a function that has the component instance as the value of this .

value is set to the state that the event handler change.

This way, the inputted values will be displayed.

A better way to do it is to set the name dynamically with computed property keys.

For example, we can write:

class Form extends React.Component {
  constructor() {
    this.state = {};
  }


  handleChange(propertyName, event) {
    const contact = this.state.contact;
    contact[propertyName] = event.target.value;
    this.setState({ contact: contact });
  }

  render() {
    return (
      <div>
        <input type="text" onChange={this.handleChange.bind(this, 'firstName')} value={this.state.contact.firstName}/>
        <input type="text" onChange={this.handleChange.bind(this, 'lastName')} value={this.state.contact.lastName}/>
        <input type="text" onChange={this.handleChange.bind(this, 'phone')} value={this.state.contact.phone}/>
      </div>
    );
  }
}

We have one change handler for all 3 inputs.

Then we can pass in the field as the 2nd argument of bind to set that as the first argument of the handler.

Conclusion

We can edit the input values of multiple controlled input components by providing their own change handlers.

Categories
React Answers

How to Clear an Input Value After Form Submit in a React Component?

Sometimes, we want to clear an input value after form submit in a React component.

In this article, we’ll look at how to clear an input after form submit in a React component.

Clear an Input Value After Form Submit in a React Component

We can clear an input value after form submit in a React component.

To do that, we write:

onHandleSubmit(e) {
  e.preventDefault();
  const name = this.state.name;
  this.props.searchByName(name);
  this.setState({
    name: ''
  });
}

We call preventDefault to stop the default submit behavior.

Then we get the name from the state which is what we inputted.

Then we call our search function.

And finally, we clear the input value by clearing the name state by assigning it an empty string.

Conclusion

We can clear an input value after form submit in a React component.

Categories
React Answers

How Add a
Tag in React Between Two Strings in a React Component?

Sometimes, we want to add a <br> tag between 2 strings i a React component.

In this article, we’ll look at how to add a <br> tag between 2 strings i a React component.

Add a <br> Tag Between Two Strings in a React Component

We can add a line break character in a string to add a line break.

Then we can use the white-space: pre-line style to make them display.

For instance, we can write:

render() {
   message = `Hello n World.`;
   return (
       <div className='new-line'>{message}</div>
   );
}

in our component.

Then we can add the following CSS:

.new-line {
  white-space: pre-line;
}

Conclusion

We can add a line break character in a string to add a line break.

Then we can use the white-space: pre-line style to make them display.