React Basics
- React.Fragment or can be used to wrap the JSX of a component, so we don't have to use a div
- map method can be used to render a list of objects as JSX code.
- We may use functions to handle events like onClick() . For example, if we want to run handleClick when clicked, it has to be implemented as below:
<button onClick={handleClick} >Click Me</button>
- If you need to pass a value as parameter to handleClick function, implement as below:
<button onClick={()=> {handleClick("helloworld"} >Click Me</button>
Props
- There's a special prop in react called 'children'. If you want to put some JSX content between the opening and closing Tags of a custom component, you can accept children prop in the custom component and render the children in it's JSX body
- No matter how many props we send, the component recieves a single param (which is generally called 'props'). We can destructure them.
- Props can be sent in different ways
{
let name="player 1"
let symbol = "X"
}
<Player name={name} symbol={symbol} />
{const player = {
"name": "vinay",
"symbol": "X"
}}
<Player {...player} />
- If we want to send attributes for the container of the component as a prop, we can receive and destructure them as name, age, ...prop and can set the ...prop as attribute enclosed in flower brackets for the container element.
Styles
CSS Styles are global. If you declare a style in SideBar.css for a
, it would reflect for all tags in the application. To solve this we have various methods.- Write Inline CSS
- Use a library
- Choose the class names wisely and make sure that they don't collide.
- Use css modules. Rename the SideBar.css file with SideBar.module.css.
import {styles} from './SideBar.module.css'
function SideBar(){
return(
<div className={styles.info}></div>
);
}
- Use a package called styled-components. It also passes the props declared in the component to underlying tag. The props includes child elements.
import {styled} from 'styled-components'
const MyCustomDiv = styled.div`
display: flex;
margin-bottom: 0.5rem;
`
export default App(){
return (
<MyCustomDiv>Hello</MyCustomDiv>
)
}
Context API
- Create a context
<!--store.js-->
import { createContext } from "react";
export const CartContext = createContext({
items:[],
})
- Now, in App.js, wrap your code with CartContext.Provider with a value
import {CartContext} from "./store.jsx";
const [cartState, setCartState] = useState(
items:[]
)
return (
<CartContext.Provider value={items: []}>
<p>Hello</p>
</CartContext.Provider>
)
- Now, the cart data can be used across all components without having to send it via props. But, how do we update the state without props? For that, we create a CartContextProvider function in the store file, accept children and wrap this function around the content in App file. You'll make use of reducer to update context.