1

There are three text boxes in my app all three are having same functionality like When onChange Function happened.. I will change the state from empty to the current target value of the text box. I did like below seems to be elementary level. can you please help me to do it in react way?

updateBugChange = (e, type) => {
    if(type === 'title')
    {
        this.setState({ bugTitle : e.target.value })
    }
    if(type === 'type')
    {
        this.setState({ bugType : e.target.value })
    }
    if(type === 'description')
    {
        this.setState({ bugDescription : e.target.value })
    }
}

1 Answer 1

1

We can create the mapping between the types and field names, and then use again computed property feature of JS. This choice is loosely bounded.

updateBugChange = (e, type)=>{
    const mapping = {
        title: 'bugTitle',
        type: 'bugType',
        description: 'bugDescription'
    }

    if(!mapping[type]) return;

    this.setState({
        [mapping[type]]: e.target.value
    })
}
Sign up to request clarification or add additional context in comments.

6 Comments

The first code has two bugs: toUpperCase isn't called, and anyway it would return bugTITLE, etc., not bugTitle. The second example has bugTitle twice in the mapping.
In addition, for the second example it would be a very good idea to check whether the property name got defined from the mapping; otherwise you'd be wondering why there's a state key called undefined if something goes wrong.
can u please have a look into this jsfiddle.net/5yLts8q6 i didnt add it properly i hope u can understand
@AKX Thanks for the feedback, and I removed the short version. Updated the code now. I didn't add the if, by thinking that the handler will be added to fields by developers, so there is no chance to be called from arbitrary places. But now I added, still I think it is not needed, but good to have guard clause.
@AKX And then who should handle this error? I am not sure about this throwing error pattern from change handler..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.