Home > Software engineering >  Can 2 components send 2 different props to one component in react?
Can 2 components send 2 different props to one component in react?

Time:09-12

I came across one situation where I need to send a value of variable to one Component where it already having props for other purpose. Now the challenge is can 2 different components send different props to only one component? or Can we use of one variable value in another component without using props? Like function A(props1,props2) {

}

CodePudding user response:

If I understood your question right, you have e.g. a component called Foo that is called in two different places and with two different kind of properties. E.g. in one component it is called like this

<Foo test="something" />

and in another called like this:

<Foo bar={42} />

In that case you can write your component as a single function, but need to check your provided arguments. In React you should only make use of the first provided parameter, which is an object of arbitrary shape. So this could look like that:

const Foo = (props) => {
  if ("test" in props) {
    return <div>{props.test}</div>;
  } else {
    return <span>Given number is: {props.bar}</span>
  }
  
};

CodePudding user response:

You can send props from anywhere to the component, and it will respond accordingly, for example, if you send "Component a={1}" and "Component a={2} b={1}", both the call will have a separate process and will react accordingly.

CodePudding user response:

Yes they can

const Data = ({data}) => {
       console.log(data);
  }

<Data data='hello world'/> //it will print hello world
<Data data = 'Bye world'/> //it will print bye world

  • Related