Props is used when React componets want to communicate (see another component's state, pass down the value ... etc) each other. For instance, className, src, alt, width, and height are props we usually used.
function Avatar() {
return (
<img
className="avatar"
src="https://i.imgur.com/1bX5QH6.jpg"
alt="Lin Lanying"
width={100}
height={100}
/>
);
}
export default function Profile() {
return (
<Avatar />
);
}
In the code above, the tag is recieving the props.
export default function Profile() {
return (
<Avatar />
);
}
In the code above, there is no props yet for the tag. How can parent component Profile can pass props to its childe tag Avatar?
export default function Profile() {
return (
<Avatar
person={{ name: 'Lin Lanying', imageId: '1bX5QH6' }}
size={100}
/>
);
}
First, just pass the props you want to. In this case, Avatar got an object prop 'person' and number prop 'size'.
Second, you have to allow the 'Avatar' ro read the props it got. So that it can use the props passed from their parent component.
function Avatar({ person, size }) {
// person and size are available here
}
import { getImageUrl } from './utils.js';
function Avatar({ person, size }) {
return (
);
}
export default function Profile() {
return (
<div>
<Avatar
size={100}
person={{
name: 'Katsuko Saruhashi',
imageId: 'YfeOqp2'
}}
/>
<Avatar
size={80}
person={{
name: 'Aklilu Lemma',
imageId: 'OKS67lh'
}}
/>
<Avatar
size={50}
person={{
name: 'Lin Lanying',
imageId: '1bX5QH6'
}}
/>
</div>
);
}
Now it is able to use the component with props.
if you want to assign value that would be assigned when there's no prop to be assigned, you can use 'default props'.
import React from "react";
export default function Hello({ name, color }) {
return <div style={{ color }}>Hello {name}</div>;
}
Hello.defaultProps = {
name: "no name",
};
In this code, when there's no 'name' for this component 'Hello', property 'no name' will be assigned for it.
If you want to see the components between the tag you used, you can see them with calling 'props children'.
import logo from "./logo.svg";
import Hello from "./hello";
import Wrapper from "./Wrapper";
import "./App.css";
function App() {
return (
<div className="App">
<Wrapper>
<Hello name="react" color="red" />
<Hello color="pink" />
</Wrapper>
</div>
);
}
export default App;
import React from 'react';
function Wrapper() {
const style = {
border: '2px solid black',
padding: '16px',
};
return (
<div style={style}>
</div>
)
}
export default Wrapper;
When I make run this, I can only see the box with the black border. Why? Because it didn't know the children tags below or between this tags (when used)
So, you can fix this by rendering the children with {children.props}
import React, { Children } from "react";
export default function Wrapper({ children }) {
const style = {
border: "2px solid black",
padding: "16px",
};
return <div style={style}>{children}</div>;
}
When it comes like this, you can now see the children tags too.