Changing the text on webpage in real time in React JS

Lets see how we can change the text of a paragraph element if we make change in a Text box on our react webpage. Whatever you type in the text box, the same text will get reflected on the paragraph element in real time.

For that we nee to add one more element to our Employee.js file. We will try to change the profession of an employee by typing it in text box. We have added text box in below code and used onChange event so whenever a change happens in the text box, a method will be triggered. To get the method, here we will pass the reference of that method to props (props.professionChanged), like we did in previous posts.


Employee.js

When we write ‘value={props.profession}’ in our input text box. The initial text value inside the text box doesn’t show blank. The value will be fetched from our current state which is ‘Developer’


App.js

We will have to make some changes to the professionChangeHandler so that whatever we type in our text box, that text should get transferred to our setState() method. The event.target refers to element(in our case its a text box), the event occurred on and event.target.value will return the text that we provide in our text box. Also we have to create a new props ‘changedProfession’, which we will pass to Employee.js. This new props will hold the reference to our ‘changeProfessionHandler’. We are using event object here to extract the text value typed by user in our input text box

Lets do it in a much simpler way

We can achieve the same thing by using only App.js file and not introducing another component. We will only use a state and have a state there named userInput. Initially it will be a blank string, later on we will store user typed string into this state.

We also have to create an input field where user can type anything and we will create an event handler which will be called whenever a change happens in that input field, call it inputChangedHandler. Above we have created a state named userInput. We can access it by using {this.state.userInput} for the value attribute of input field. By this we can achieve two way binding.

And to print whatever our user types in the input field we can again use {this.state.userInput} and put it inside paragraph tag to display on screen.