Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React 'String' prop passing down as an 'object'

I have 2 components like below in my application:

<Comp1>
...
    <Comp2 prop1='test1' prop2='test2'/>
    <Comp3 prop1='test1 />
</Comp1>

The Comp2 and Comp3 components look like below:

const Comp2 = (prop1, prop2) => {
...
...
}
Comp2.propTypes = {
prop1: PropTypes.string.isrequired,
prop2: PropTypes.string.isrequired,
}


const Comp3 = prop1 => (
...
...
)
Comp2.propTypes = {
prop1: PropTypes.string.isrequired,
}

As we can see from above, I am passing a string value 'test1' from Comp1 into 2 components - Comp2 and Comp3.

Comp2 receives a string value for 'prop1' as 'test1' - as expected.

However, Comp3 receives the same property 'prop1' as an object instead of a string. So in Comp3, prop1 is not equal to string 'test1', but it is equal to 'prop1: test1' in the shape of a Json object. I am not able to figure out why the same property is passing down as different types for both components when they are defined in a very similar manner.

Could someone please help me understand how this is going on? Thank you much in advance.

like image 580
Hello Avatar asked Oct 20 '25 03:10

Hello


1 Answers

Please remember that functional components take only one parameter and it is called props. So whatever the prop you want to access, you have to reference it as props.prop. In your components, you can take these values with object destructuring as shown below.

const Comp2 = ({prop1, prop2}) => {
...
...
}

const Comp3 = ({ prop1 }) => (
...
...
)

So your error is expected, because you are taking props which is an object.

like image 81
FurkanO Avatar answered Oct 22 '25 06:10

FurkanO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!