Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple props to React component

Tags:

I am trying to pass two argument using props in ImageText component.
I am not sure if it is right method or I have to create a map and then pass it.

import React, { PropTypes, Component } from 'react'  const ImageText = () => (     <div className="img-with-text">         <img  className="img" src={props.imageUrl} />         <p className="txt">{props.imageText}</p>     </div> );  export default ImageText; 

Calling this component from another as follows

<ImageText imageUrl="/js.com" imageText="food"/> 

But is throwing error as

Uncaught (in promise) ReferenceError: props is not defined     at ImageText 
like image 406
mary_jane Avatar asked Dec 27 '16 06:12

mary_jane


People also ask

How do you pass more than one prop in React?

Method 1: We can make a separate method for the event and call all the props method in that method. Method 2: We can create an anonymous function and call all the props method inside the anonymous method.

Can we pass multiple props?

Props passing. As the code above demonstrates, you can pass props between components by adding them when the component is being called, just like you pass arguments when calling on a regular JavaScript function .

How do you pass props from one component to another in React hooks?

Just call an alert method in the childToParent function and pass that function as a prop to the child component. And in the child component, accept the childToParent function as a prop. Then assign it to an onClick event on a button. That's it!


2 Answers

In your case issue with you are using "Arrow functions" which needs to pass params inside brackets

const ImageText = () => ( 

Should be

 const ImageText = (props) => ( 

Now

let props = { imageUrl:"/js.com", imageText:""food"" } <ImageText {...props} /> 

Access inside ImageText like

{props.imageUrl} or {props.imageText} 
like image 187
BEJGAM SHIVA PRASAD Avatar answered Oct 04 '22 12:10

BEJGAM SHIVA PRASAD


When you define your component like that, you need to pass your props as parameters to the anonymous function:

const ImageText = ({imageUrl, imageText}) => ( ... rest of the code ... );

like image 30
Cornel Janssen Avatar answered Oct 04 '22 11:10

Cornel Janssen