pass props react code example
Example 1: create react component class
class MyComponent extends React.Component{
constructor(props){
super(props);
};
render(){
return(
<div>
<h1>
My First React Component!
</h1>
</div>
);
}
};
Example 2: react pass props to children
import React, { Children, isValidElement, cloneElement } from 'react';
const Child = ({ doSomething, value }) => (
<div onClick={() => doSomething(value)}>Click Me</div>
);
function Parent({ children }) {
function doSomething(value) {
console.log('doSomething called by child with value:', value);
}
render() {
const childrenWithProps = Children.map(children, child => {
if (isValidElement(child)) {
return cloneElement(child, { doSomething })
}
return child;
});
return <div>{childrenWithProps}</div>
}
};
ReactDOM.render(
<Parent>
<Child value="1" />
<Child value="2" />
</Parent>,
document.getElementById('container')
);
Example 3: pass props in react
const expression = 'Happy';
<Greeting statement='Hello' expression={expression}/>
class Greeting extends Component {
render() {
return <h1>{this.props.statement} I am feeling {this.props.expression} today!</h1>;
}
}
Example 4: pass props
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Example 5: defining props in react
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Sara" />;
ReactDOM.render(
element,
document.getElementById('root')
);
Example 6: react pass parameter to component
import React, { Component } from 'react'; class App extends Component { render() { return ( <div> <Greeting /> </div> ); }} class Greeting extends Component { render() { const greeting = 'Welcome to React'; return <h1>{greeting}</h1>; }} export default App;