0
render() {
    return (
        <input
            onChange={this.handleChange}
            value={this.props.transcript}
            type='text
        />
    )    
}

in the above example, If text value is changed using keyboard inputs, it will trigger onChange event, but if it's being changed dynamically via this.props.transcript, onChange event is not triggered. How to solve this issue?

techKid-Rinshad
  • 177
  • 1
  • 2
  • 9
  • Why would you need on change on that? it seems unnecessary requirement. – Just code Dec 08 '18 at 10:38
  • because I want to trigger the onChange event both for keyboard input changes and as well as when the this,props.transcript changes @Justcode – techKid-Rinshad Dec 08 '18 at 10:42
  • This might help you. https://stackoverflow.com/questions/136617/how-do-i-programmatically-force-an-onchange-event-on-an-input – anurag145 Dec 08 '18 at 11:03
  • 1
    Look in to the `componentDidUpdate` method (https://reactjs.org/docs/react-component.html#componentdidupdate) - which gives you access to the previous props so you can compare the `props.transcript` value to see if it's changed, and call `this.handleChange` if needed. – Brett DeWoody Dec 08 '18 at 11:18

3 Answers3

0

If we are using react setState correctly it should work without issue but, Look like you have two sets of values one coming from parent "this.props.transcript" and one in input box which is handled by "this.handleChange". Alternately, check need of react hooks like "componentWillUpdate" and "componentWillReceiveProps" to apply state change on input.

Mukund
  • 393
  • 2
  • 7
0

Without seeing more of the code, it looks like your value for transcript in the input is wrong.

Try value={props.transcript} and if that doesn’t work value={this.state.transcript}.

Nick Buzzy
  • 115
  • 9
0

You can use componentWillReceiveProps hooks to achieve it, as your props get updated it will call componentWillReceiveProps method. Inside the method it is your playground. Please make sure this method will be called on each and every time the props changes

import React,{ Component } from 'react'

class InputBox extends Component {
    componentWillReceiveProps(nextProps){
        // write your logic here or call to the common method
        console.log(nextProps.transcript);
    }
    handleChange(e){
        console.log(e.target.value)
    }
    render(){
        return(
            <section>
                <input
                    onChange={this.handleChange}
                    value={this.props.transcript}
                    type='text'
                />
            </section>
        );
    }
}

export default InputBox;
Aamin Khan
  • 712
  • 4
  • 12