Introducing props

So, what are props? Props are shorthand for properties, and as you can guess, they define properties inside of our React components. Generally speaking, these get passed in from the parent, although they can get passed in from anywhere, truth be told.

Right now, we're just using a simple functional component, and that function doesn't specify any arguments as part of its signature, so if we want to start using props we'll have to change that first.

Let's open up our Todo component in src/Todo.js, and change the function declaration to also pass in a props argument:

const Todo = props => {

This would roughly be the equivalent of us writing the following in vanilla JavaScript:

function Todo(props) {

Next, we'll have to change the display text to actually use something from our props argument, so we'll add a reference to {props.description}:

const Todo = props => <div className="Todo">{props.description}</div>;

Save the file, because now we'll have to head back over to our primary App component (src/App.js) and start passing in the description as part of the properties passed in to our Todo components:

const App = () => (
<div className="App">
<h2>Todoifier</h2>
<br />
<Todo description="Do the thing" />
<Todo description="Do another thing" />
</div>
);

After saving the file and seeing the browser window refresh, we should expect to see the properties we just entered now show up in the browser, as follows:

And there we are! Reusable, modifiable components, done with almost no effort at all!

The even better part is that any changes to props will trigger React to re-render that component (depending on what changed and where it changed). This is something that is profoundly useful, especially when you factor in that the old world had you checking for changes, and then trying to either delete and recreate elements on the fly or try to sneak the changes in without having to remove it all away.

Props are great, overall, but if we want to do something a little more permanent and something that is better for storing how something changes over time, we need to introduce the concept of state. Instead of props, state is meant to be used for something that is changing all of the time, generally local to a single component; you'll pass the state down to child components that need it via props.

The trouble is that we're currently using functional components, which is fine for now, but the minute we want to start tracking any sort of internal state, we'll need to switch to a different method of creating our React components.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.95.38