JokerBean
JokerBean

Reputation: 423

Can we pass more than one props from a stateless component and get it as single arguments in another stateless component in react?

I am trying to pass more than one props to a functional component and getting in the component as single argument props but getting error in InputBox component at placeholder as item is undefined

export default ({change, state}) => (
  <div style={styles.container}>
    <h3 style={{margin: 0, marginBottom: 15}}>InputData</h3>
    {items.map((item) => (
      <div style={styles.lineContainer}>
        {(() => {
          switch(item.name) {
            case "name1": return <InputBox handleChange ={change} state ={state} item={item}/>
            case "name2": return <SelectBox handleChange ={change} state ={state} item={item}/>;
            case "name3": return <SelectBox handleChange ={change} state ={state} item={item}/>;
            default: return <InputBox/>
          }
        })()}
      </div>
    ))}
  </div>
);


const InputBox = props => 
     <input
        type="text"
        placeholder={props.item.place}
        name={props.item.name}
        value={props.state[props.item.name]}
        onChange={props.change}
        required
        style={{height: 20}}
/>

Upvotes: 0

Views: 78

Answers (3)

Sania Khushbakht Jamil
Sania Khushbakht Jamil

Reputation: 822

There are more than one problems with your code.

  1. in your first component, where the line is items.map((item)=>...., items is not defined anywhere. Assumption: maybe you had to destructure it from state or get another prop.

  2. Your component InputBox is expecting some props, i.e., in const InputBox = props =>.... And these props are not being passed from default: return <InputBox/>, just like you did in case "name1".

P.S, you can define default props if you don't have any intentions of sending props to <InputBox />.

Upvotes: 3

Manu
Manu

Reputation: 10934

As I can make out, this is happening because for default case in switch you are returning <InputBox/> without any props but inside your InputBox component you are trying to refer to a prop using props.item.place. Hence this error.

Either make sure that switch returns appropriate value for default case or configure component to adjust to props.

Upvotes: 1

aditya81070
aditya81070

Reputation: 736

I don't see any items array in your default export. I think you forgot to destruct it from your state.

Use state.items.map(...) instead of items.map(...) in your default export.

Upvotes: 0

Related Questions