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.

Categories
React Answers

How to Add Click Event Handlers for Divs in React?

Oftentimes, we want to add click event handlers to div elements in our React components.

In this article, we’ll look at how to add click event handlers to div elements in our React components.

Add Click Event Handlers for Divs in React

We can use onClick with divs if we provide it a size.

For instance, we can write:

class App extends React.component {
  constructor() {
    this.state = {
      color: 'black'
    };
  },

  changeColor() {
    const newColor = this.state.color == 'white' ? 'black' : 'white';
    this.setState({
      color: newColor
    });
  },

  render() {
    return (
       <div>
          <div
             style = {{
                background: this.state.color,
                width: 100,
                height: 100
             }}
             onClick = {this.changeColor}
          >
          </div>
      </div>
    );
  }
}

We create a div with a background by passing in an object with the styles in the style prop.

We set the width and height to 100px so that we can display a div with nothing inside.

Then we can pass in a click handler to the onClick prop.

In the changeColor method, we just toggle between white and black for the color state.

Conclusion

We can use onClick with divs if we provide it a size.