Skip to content

Instantly share code, notes, and snippets.

@annelyse
Last active September 20, 2022 15:50
Show Gist options
  • Save annelyse/c15fdc3d76e34a83ab5fa88d16061d21 to your computer and use it in GitHub Desktop.
Save annelyse/c15fdc3d76e34a83ab5fa88d16061d21 to your computer and use it in GitHub Desktop.
// stateless functional component.
// For now, think of a stateless component as one that can receive data and render it, but does not manage or track changes to that data. (We'll cover the second way to create a React component in the next challenge.)
// name of component :requires your function name to begin with a capital letter.
const DemoComponent = function() {
return (
<div className='customClass' />
);
};
const ShoppingCart = (props) => {
ShoppingCart.defaultProps = {
items: 0
};
return (
<div>
<h1>Shopping Cart Component</h1>
</div>
)
};
// Change code below this line
Dans une stateless fonction, il n'y a pas de render, ni de constructor
The other way to define a React component is with the ES6 class syntax. In the following example, Kitten extends React.Component:
class Kitten extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h1>Hi</h1>
);
}
}
This creates an ES6 class Kitten which extends the React.Component class. So the Kitten class now has access to many useful React features, such as local state and lifecycle hooks
Also notice the Kitten class has a constructor defined within it that calls super(). It uses super() to call the constructor of the parent class, in this case React.Component.
The constructor is a special method used during the initialization of objects that are created with the class keyword.
Render multiple element :
return (
<App>
<Navbar />
<Dashboard />
<Footer />
</App>
)
const ChildComponent = () => {
return (
<div>
<p>I am the child</p>
</div>
);
};
class ParentComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>I am the parent</h1>
<ChildComponent/>
</div>
);
}
};
// Component composition
class TypesOfFood extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>Types of Food:</h1>
{/* Change code below this line */}
<Fruits />
<Vegetables />
{/* Change code above this line */}
</div>
);
}
};
// Change code below this line
ReactDOM.render(<TypesOfFood />, document.getElementById('challenge-node'))
// Change code below this line
class MyComponent extends React.Component{ 
constructor(props){
super(props);
}
render(){
return(
<div>
<h1>My First React Component!</h1>
</div>
)
}
}
ReactDOM.render(<MyComponent />, document.getElementById('challenge-node'))
//fonction javascrip dans du JSX:
// <CurrentDate date={ Date()} />
const CurrentDate = (props) => {
return (
<div>
{ /* Change code below this line */ }
<p>The current date is: {props.date} </p>
{ /* Change code above this line */ }
</div>
);
};
class Calendar extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>What date is it?</h3>
{ /* Change code below this line */ }
<CurrentDate date={ Date()} />
{ /* Change code above this line */ }
</div>
);
}
};
//
To pass an array to a JSX element, it must be treated as JavaScript and wrapped in curly braces.
<ParentComponent>
<ChildComponent colors={["green", "blue", "red"]} />
</ParentComponent>
//
const ChildComponent = (props) => <p>{props.colors.join(', ')}</p>
This will join all colors array items into a comma separated string and produce: <p>green, blue, red</p>
const List = (props) => {
{ /* Change code below this line */ }
return <p>{props.tasks.join(", ")}</p>
{ /* Change code above this line */ }
};
class ToDo extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>To Do Lists</h1>
<h2>Today</h2>
{ /* Change code below this line */ }
<List tasks={["walk dog", "workout"]} />
<h2>Tomorrow</h2>
<List tasks={["gym", "work", "workout"]} />
{ /* Change code above this line */ }
</div>
);
}
};
React also has an option to set default props. You can assign default props to a component as a property on the component itself and React assigns the default prop if necessary. This allows you to specify what a prop value should be if no value is explicitly provided. For example, if you declare MyComponent.defaultProps = { location: 'San Francisco' }, you have defined a location prop that's set to the string San Francisco, unless you specify otherwise.
//default props
const ShoppingCart = (props) => {
ShoppingCart.defaultProps = {
items: 0
};
return (
<div>
<h1>Shopping Cart Component</h1>
</div>
)
};
// Change code below this line
const Items = (props) => {
return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>
}
Items.defaultProps = {
quantity: 0
}
class ShoppingCart extends React.Component {
constructor(props) {
super(props);
}
render() {
{ /* Change code below this line */ }
return <Items quantity={10}/>
{ /* Change code above this line */ }
}
};
//integer in jsx
quantity={10}
//Use PropTypes to Define the Props You Expect
// https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes
import PropTypes from 'prop-types';
const Items = (props) => {
// Change code below this line
Items.propTypes = {
quantity: PropTypes.number.isRequired,
}
// Change code above this line
Items.defaultProps = {
quantity: 0
};
return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>
};
class ShoppingCart extends React.Component {
constructor(props) {
super(props);
}
render() {
return <Items />
}
};
You can set propTypes on your component to require the data to be of type array.
//Finally, a stateful component is a class component that does maintain its own internal state. You may see stateful components referred to simply as components or React components.
// A functional(a.k.a. stateless) component is just a plain javascript function which takes props as an argument and returns a react element.
const Camper = props => <p>{props.name}</p>;
Camper.defaultProps = {
name: "CamperBot"
};
Camper.propTypes = {
name: PropTypes.string.isRequired
};
// state in react component with class
// à mettre dans le constructeur
class StatefulComponent extends React.Component {
constructor(props) {
super(props);
// Only change code below this line
this.state = {
firstName : "annelyse"
}
// Only change code above this line
}
render() {
return (
<div>
<h1>{this.state.firstName}</h1>
</div>
);
}
};
// state in variable
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'freeCodeCamp'
}
}
render() {
// Change code below this line
const name = this.state.name;
// Change code above this line
return (
<div>
{ /* Change code below this line */ }
<h1>{name}</h1>
{ /* Change code above this line */ }
</div>
);
}
};
//Set State with this.setState
// React expects you to never modify state directly, instead always use this.setState() when state changes occur.
this.setState({
username: 'Lewis'
});
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Initial State'
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
name : "React Rocks!"
})
}
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
<h1>{this.state.name}</h1>
</div>
);
}
};
// this
Problem Explanation
If a method on a JavaScript class needs to access some internal state of the instance, like this.state, the method needs to be bound to the instance of the class.
class MyClass {
constructor() {
this.myMethod = this.myMethod.bind(this);
}
myMethod() {
// whatever myMethod does
}
}
exeple :
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
text: "Hello"
};
}
handleClick() {
this.setState({
text: "You clicked!"
});
}
render() {
return (
<div>
<button onClick = {this.handleClick}>Click Me</button>
<h1>{this.state.text}</h1>
</div>
);
}
};
//toggle state
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
visibility: false
};
this.toggleVisibility = this.toggleVisibility.bind(this);
}
toggleVisibility() {
this.setState(state => ({
visibility: !state.visibility
}));
}
render() {
if (this.state.visibility) {
return (
<div>
<button onClick = {this.toggleVisibility}>Click Me</button>
<h1>Now you see me!</h1>
</div>
);
} else {
return (
<div>
<button onClick = {this.toggleVisibility}>Click Me</button>
</div>
);
}
}
};
//increment value
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
// Change code below this line
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
this.reset = this.reset.bind(this);
// Change code above this line
}
// Change code below this line
increment = () => {
this.setState(state => ({
count: state.count + 1
}))
}
decrement = () => {
this.setState(state => ({
count: state.count - 1
}))
}
reset = () => {
this.setState(state => ({
count: 0
}))
}
// Change code above this line
render() {
return (
<div>
<button className='inc' onClick={this.increment}>Increment!</button>
<button className='dec' onClick={this.decrement}>Decrement!</button>
<button className='reset' onClick={this.reset}>Reset</button>
<h1>Current Count: {this.state.count}</h1>
</div>
);
}
};
//input
class ControlledInput extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ''
};
// Change code below this line
this.handleChange = this.handleChange.bind(this);
// Change code above this line
}
// Change code below this line
handleChange (event) {
this.setState({
input: event.target.value
})
}
// Change code above this line
render() {
return (
<div>
{ /* Change code below this line */}
<input value={this.state.input} onChange={this.handleChange} />
{ /* Change code above this line */}
<h4>Controlled Input:</h4>
<p>{this.state.input}</p>
</div>
);
}
};
//controlled form with submit
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
submit: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
input: event.target.value
});
}
handleSubmit(event) {
event.preventDefault();
this.setState( state => ({
submit: state.input
}));
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
{/* Change code below this line */}
<input value={this.state.input} onChange={this.handleChange} />
{/* Change code above this line */}
<button type='submit' onClick={this.handleSubmit}>Submit!</button>
</form>
<h1>{this.state.submit}</h1>
</div>
);
}
}
//The componentWillMount() method is called before the render() method when a component is being mounted to the DOM.
// The best practice with React is to place API calls or any calls to your server in the lifecycle method componentDidMount(). This method is called after a component is mounted to the DOM. Any calls to setState() here will trigger a re-rendering of your component. When you call an API in this method, and set your state with the data that the API returns, it will automatically trigger an update once you receive the data.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment