Ehsan O
Ehsan O

Reputation: 33

Changing component prop based on onBlur function in React

I have a component that I can change how it is rendered based on a prop (added a failed state, and based on whether it fails or not it turns red or stays the original color), the logic for whether failed is true or false is in the parent component.

I want to change the failed state, but only onBlur (without changing the child component). Is there a way to pass in an onBlur function that applies changes to a child prop?

I've tried a number of different things like:

Child component:

<input 
  failed={failed}
  onBlur={onBlur}
/>

Parent component:

handleBlur(value) {
  this.props.failed = value;
}

In the render function:

onBlur={() => this.handleBlur(newValue)}

But it did not work for me.

Upvotes: 0

Views: 1659

Answers (1)

Avanthika
Avanthika

Reputation: 4182

Props are data that are passed from a parent to its children and are made available through this.props in the child component.

You maintain whatever prop your are passing to child component either in parent component's state or in redux/flux state (if you have global state management).

When failed is modified, a state change should be triggered on parent component, which in-turn will trigger a re-render inside child component.

For example:

In the following, we pass failed as a prop, and onFailureUpdate function as a callback trigger to child component from parent.

class Parent extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
   failed: false
  }
 }

 onFailureUpdate = (value) => {
   this.setState({
    failed: value
   });
 }

 render() {
  return (<ChildComponent failed={this.state.failed} onFailureUpdate={this.onFailureUpdate} />)
 }
}

In child component, on blur, we are using the function we passed as prop to modify state in parent, which in-turn will re-render child component.

class ChildComponent extends React.Component {
  onBlur = (e) => {
    this.props.onFailureUpdate(e.target.value);
  }

  render() {
    return (
      <input 
        value={this.props.failed}
        onBlur={(e) => this.onBlur(e)}
      />
    )
  }
}

Other way:

Or, if there's no necessity for props or parent-child relationship, you can eliminate the need for parent container and go for state maintenance in child.

class RewrittenChildComponentWithState extends React.Component {
  constructor() {
   this.state = {
    failed: false
   };
  }

  onBlur = (e) => {
    this.setState({
     failed: e.target.value
    });
  }

  render() {
    return (
      <input 
        value={this.state.failed}
        onBlur={(e) => this.onBlur(e)}
      />
    )
  }
}

Hope this solves your confusion.

Upvotes: 1

Related Questions