In the last lesson, we had a look on props. props simply an object giving us access to all the attributes we pass to our own components. Now sometimes you don’t want to get some information from outside but you want to have it inside a component and change it from inside there too. So for example in our App.js file, let’s say we also want to ass a button which if we click it simply switches one of the names we use there
props
import React, { Component } from 'react'; import './App.css'; import Person from './Person/Person'; class App extends Component { render() { return ( <div className="App"> <h1> Heading</h1> <button>Switch Name</button> <Person name="Lucy" age="23" /> <Person name="Max" age="12"> My Hobbies : Dancing </Person> <Person name="Mike" age="34" /> </div> ); } } export default App;
But first of all we need to defines the attributes name (In App.js > Person component) in a non hardcoded way. Right now we have hardcoded into our JSX code and that is ok, But if we want to change it we have to store in some variable or something like that. Now, in class we can define variable which will be used just inside that perticular component
Person
import React, { Component } from 'react'; import './App.css'; import Person from './Person/Person'; class App extends Component { state = { persons: [ {name: 'Lucy', age: 23}, {name: 'Max', age: 12}, {name: 'Mike', age: 34}, ] } ... } export default App;
the declared data is the state, we can now access a property like state and that is not just true but for any property in our render() method by simplying outputting something dynamic wit single curly braces …
state
render()
... class App extends Component { state = { persons: [{ name: 'Lucy', age: 23 }, { name: 'Max', age: 12 }, { name: 'Mike', age: 34 }], }; render() { return ( <div className="App"> <h1> Heading</h1> <button>Switch Name</button> <Person name={this.state.persons[0].name} age={this.state.persons[0].age} /> {/* this. reffers to this class */} {/* goes on till number of persons in array*/} </div> ); } } export default App;
if you run the application in the browser you will see a new button which does nothing and you will see the data is been output with the state variable which we declare in class. As I said state would be a special property. thus the far way we don’t use in a special way through we can change this. the state can be changed and if it changes and that is the special thing about it and it only works on that state property. if it changes it will lead react to re-render our DOM or to update the DOM I should say. So if we changed the name of Lucy if, for example, this will lead to this being re-rendered. we will see in the next lesson the click event on clicking on the button for changing the state.