DEV Community

Sarah Thompson
Sarah Thompson

Posted on

Learning React: Props

React is an open source popular web frame work from Facebook that I've been itching to learn - and I want to drag you along for the ride. One of the key parts of react to learn are Props.

Props is a special keyword that is short for property. It is an object, and like all JavaScript objects all the attributes can be grabbed by the dot . notation. Props are things you pass to a function or what you want to initialize your component with.

Props can be used for that data can be dynamically passed to children components, and must never be changed/mutated directly. With props we are expecting that for every input we should be able to expect the same output. Every React components should act like pure functions with respect to their props.

First things first, can define our own attributes to assign values to HTML elements with interpolation { } like <div station={stationName} />.

Below is an example of props being used to dynamically pass data from the parent component to the child component using interpolation on the html element in the parent component that represents the child component. Props is the object that the component receives as an argument. In this case we are passing the argument song down to the child component.

///PARENT
const song = "Stairway to Heaven";

ReactDOM.render(
  <Radio song={song} />,
);

// Child Function Component
function Radio(props) {
  return <h3>I'm listening to {props.song}</h3>;
}
Enter fullscreen mode Exit fullscreen mode

The Child component is then able to use the JavaScript object that was defined in it's parent component to display to the user what song they are listening to.

The props argument doesn't need to be actually named props, you could call it which ever variable makes sense for keeping track of the content in the props.

If you do want to update something set in a prop - but you don't want to go against the rule that they are not supposed to be mutable - you can use state!

W3 has more information on props.

Discussion (1)

Collapse
gustavogarciapereira profile image
Gustavo Garcia Pereira

Very Nice