xxxxxxxxxx
const Header = (props) => {
return (
<header>
<h1>{props.title}</h1>
</header>
)
}
export default Header
xxxxxxxxxx
const Parent = () => {
return (
<Child componentToPassDown={<SomeComp />} />
)
}
const Child = ({ componentToPassDown }) => {
return (
<>
{componentToPassDown}
</>
)
}
xxxxxxxxxx
import React from "react";
import ReactDOM from "react-dom";
function App() {
return <Greeting name="Nathan" />;
}
function Greeting(props) {
return (
<p>
Hello! I'm {props.name}, a {props.age} years old {props.occupation}.
Pleased to meet you!
</p>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
xxxxxxxxxx
/* PASSING THE PROPS to the 'Greeting' component */
const expression = 'Happy';
<Greeting statement='Hello' expression={expression}/> // statement and expression are the props (ie. arguments) we are passing to Greeting component
/* USING THE PROPS in the child component */
class Greeting extends Component {
render() {
return <h1>{this.props.statement} I am feeling {this.props.expression} today!</h1>;
}
}
xxxxxxxxxx
function Parent() {
const [name, setName] = useState('John');
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<h1>Parent Component</h1>
<Child name={name} onChange={handleChange} />
</div>
);
}
function Child(props) {
return (
<div>
<h2>Child Component</h2>
<input type="text" value={props.name} onChange={props.onChange} />
</div>
);
}
xxxxxxxxxx
function Parent({children}) {
return (
<div>
{children}
</div>
);
}
export default function App() {
const Title = () => {
return <h2>Hello world</h2>;
};
return (
<div>
<Parent>
<Title />
</Parent>
</div>
);
}
xxxxxxxxxx
const Label = props => <span>{props.children}</span>
const Button = props => {
const Inner = props.inner; // Note: variable name _must_ start with a capital letter
return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>
xxxxxxxxxx
// These two are equivalent in JSX for disabling a button
<input type="button" disabled />;
<input type="button" disabled={true} />;
// And these two are equivalent in JSX for not disabling a button
<input type="button" />;
<input type="button" disabled={false} />;
xxxxxxxxxx
//parent
const Parent = ({ children }) => {
const [checked, setChecked] = useState(false);
const allChildren = React.Children.map(children, (child) => {
const clone = React.cloneElement(child, {
checked,
setChecked,
});
return clone;
});
return allChildren;
};
//child
const Child = ({ checked, setChecked }) => {
return (
<div onClick={() => setChecked(!checked)} style={{ color: "red" }}>
child content
</div>
);
};
//app
<Parent>
<Child />
</Parent>
xxxxxxxxxx
const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />