React Props

Props are like function arguments, and you send them into the component as attributes. Props are passed to components via HTML attributes. React Props are like function arguments in JavaScript and attributes in HTML Passing props is how information flows in React apps, from parents to children.

To send props into a component, use the same syntax as HTML attributes:

const homeElement = <Home name="Folau" />;
class Home extends React.Component {
  render() {
    return <h2>Hi, my name is {this.props.name}!</h2>;
  }
}

 

Pass data

class Home extends React.Component { 

  render() { 
   return <h2>I am a {this.props.userInfo.name}!</h2>; 
  } 
} 

class Profile extends React.Component { 
  render() { 
   const userInfo = {name: "Folau"}; 
   return ( <div> <Home userInfo={carinfo} /> </div> ); 
  } 
} 

ReactDOM.render(<Profile />, document.getElementById('root'));

What Exactly Should Be Passed as a Prop?

Props can accept all sorts of things: Numbers, Booleans, Strings, Objects, even Functions. Early on you might start to wonder, should you pass an object and let the component extract what it needs? Or should you pass the specific pieces of data that the component requires?

You won’t use all of an object attributes in most cases.

It’s a good idea to keep the knowledge of data structures contained to as few places as possible to reduce the cost of change.

Props in Constructor

If your component has a constructor function, the props should always be passed to the constructor and also to the React.Component via the super() method.

React Props are read-only! You will get an error if you try to change their value.

Communicating With Parent Components

If you can’t change props, but you need to communicate something up to a parent component, how does that work?

If a child needs to send data to its parent, the parent can inject a function as a prop, like this:

function handleAction(event) {
  console.log('Child did:', event);
}

function Parent() {
  return (
    <Child onAction={handleAction}/>
  );
}

function Child({ onAction }) {
  return (
    <button onClick={onAction}/>
  );
}

The Child component receives a prop named onAction, which it can call whenever it needs to send up data or notify the parent of an event. You’ll notice that the built-in button element accepts an onClick prop, which it’ll call when the button is clicked. 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *