I'm starting to use Props in React, but I don't understand its use. Start with something simple that is to show a message by console. In one component there is the button and in the other component the message, but I don't get anything.
Component 1
//Recibo la funcion "tocar" por props que viene desde el segundo componente
export const PrimerComponente = ({tocar}) => {
return (
<>
<h2>Soy el primer Componente</h2>
<button onClick={tocar}>Enviar</button>
</>
)
}
Second Component
const SegundoComponente = () => {
const tocar = () =>{
console.log("Me presionaste");
}
return (
<>
<h2>Soy el segundo Componente</h2>
<PrimerComponente
tocar={tocar}
/>
</>
)
}
export default SegundoComponente
My other question taking advantage of the post. How do I know who is the parent and child component? Is there any convention to identify them or does it depend entirely on who passes components to whom?
Can parameters or functions be passed from one component to another bidirectionally? That is, both send parameters to each other at runtime.
Source: https://es.reactjs.org/docs/components-and-props.html
In other words, props are the properties that you pass to your components in the form of html attributes in order to display information on the user's screen.
The idea of the component is to have a little piece of your website, see a calendar, form, modal, navbar or table, that its code is written only once, and this in turn can be used in different parts of your website.
Many times you will have the need to use the same component but display different data according to what you need.
This is where the props come in, let's say we have the User component, that component displays a with the user's name on the screen.
The User component:
Inside app.js I declare the User component but I pass different props to it:
I get:
Specifically accessing a prop with curly braces is fine, but in general you'll want to receive all props within your component and if you du
Sending multiple props:
You access props with javascript dot notation:
You'll get:
For react everything is a component, the idea of react is to create a component hierarchy where the data is sent from the parent to or to the children, the react documentation has a guide explaining this, however it is not clear to me, that's why I recommend you I recommend you watch this video