DEV Community

dannohh
dannohh

Posted on

React MD

JSX

JSX produces React Elements. It isn't HTML even though it looks similar. It comes with the full power of JS. Instead of separating concerns by file type, React separates concerns by Component. You can put any JS expression in a JSX element by using curly braces ๐Ÿ‘‰ {x + 5*}* ๐Ÿ‘ˆ

If a JSX element is empty (<div></div>), you can close it immediately like this <div />
Enter fullscreen mode Exit fullscreen mode

Rendering React Elements

Elements are the smallest building blocks of React. React Components are made up of Elements. Elements are immutable and represent the UI at a certain point in time.

Components and Props

Components can feel like JS functions. They take an argument called "Props" and describe what an application element should look like. Users of React can define their own components. They will look like HTML but with custom names defined by the user.

render() {
    return (
        <MyCustomReactElement />
    )
}
//The custom component can have custom "attributes", also defined by the user
Enter fullscreen mode Exit fullscreen mode

Always start component names with a capital letter.

All React components must act like pure functions with respect to their props.

State and Lifecycle

State is similar to props (short for properties of a React Element) except that it is PRIVATE and fully controlled by the component.

State is an object declared inside the component with key: value pairs.

Whenever a component is rendered for the first time, the term is "mounted"

                                                                                                                                             ๐Ÿ‘†

                                                                           **๐Ÿ‘‰ComponentDidMount(), or later...useEffect()** 
Enter fullscreen mode Exit fullscreen mode

Special methods we can declare inside the component to run some code after the component mounts are called Lifecycle methods.

Handling Events

Pass camelCased functions inside curly brackets as React element event handlers. Like this...

<Button onClick={doSomething} /> //Notice no parenthases
Enter fullscreen mode Exit fullscreen mode

Keep in mind that preventDefault() must be explicitly called if you want to prevent default behavior of a component.

Lifting State Up

If two or more components need to reflect shared data, "lift their state" up to their next common ancestor โ†’ parent possibly

I think this can be explained best with an example...Lets try...

<CustomComponentOne /> //I hold some state to display
<CustomComponentTwo /> //I also show the same state as CustomComponentOne

<CustomComponentHolder /> // I render the above two components, so I could hold their states
Enter fullscreen mode Exit fullscreen mode

Top comments (0)