React conditional style on custom click - javascript

I am trying to change a class when onClick event is fired, my function is called and it seems to be working but the class just won't update un the render, this is my code:
import React from 'react';
const Something = props => {
let opened = false;
const toggle = () => {
opened = !opened;
};
return (
<div className={opened ? 'some-class opened' : 'some-class'}>
<div className="some-inner-class" onClick={toggle}>
...content
</div>
</div>
);
};
export default Something;
I just want to be able to change style on when click event is fired.

My suggestion to you will be to use react hooks in this scenario, by that I mean, something like this, I have updated your code with my suggestion;
Hope it helps;
import React, { useState } from 'react';
const Something = props => {
// ***because this doesn't exist in a function component and we'd want to persist this value of opened between function call, a react hook in a function component will be ideal in your case.
//let opened = false;
// *suggestion as per react documentation: useState hook lets us keep local state in a function component
const [opened, setOpened] = useState(false);
// ***you don't really need this part, see my approach in second div of return
// const toggle = () => {
// opened = !opened;
// };
return (
<div className={opened ? 'some-class opened' : 'some-class'}>
<div className="some-inner-class" onClick={() => setOpened(true)}>
<p>Click me</p>
</div>
</div>
);
};
export default Something;

You need to update state in React for a rerender to occur. You should be creating state in a constructor like:
constructor() {
super();
this.state = { toggled: false };
}
Then, in your toggle function you need to call
this.setState({toggled: !this.state.toggled});
Currently your component is a stateless functional component so you would either need to rewrite it as a class that extends React.component or you could use hooks, https://reactjs.org/docs/hooks-state.html. Since it looks like you're just starting to learn how to use React I would rewrite the component as a class first and then try to refactor it using hooks (the modern practice).

Related

useState setter function is not updating state in react

I am using the useIsDirty hook in two components, CustomCodeEditor and EditorFooter, to track whether the code in the Editor has been modified. The hook returns an isDirty state and a setIsDirty function to update it. When I call setIsDirty(true) in the CustomCodeEditor component, the state is updated, but when I call setIsDirty(false) in the EditorFooter component, it doesn't seem to update the isDirty state. I believe this is because the EditorFooter component does not have access to the updated state. Anyone, please help me with this.
useIsDirty:
import { useEffect, useState } from "react"
const useIsDirty = () => {
const [isDirty, setIsDirty] = useState(false)
useEffect(() => {
const handleBeforeUnload = (event) => {
if (isDirty) {
event.preventDefault()
event.returnValue = ""
alert("You have unsaved changes, are you sure you want to leave?")
}
}
console.log("Diryt:", isDirty)
window.addEventListener("beforeunload", handleBeforeUnload)
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload)
}
}, [isDirty])
return { isDirty, setIsDirty }
}
export default useIsDirty
CustomCodeEditor
import Editor from "#monaco-editor/react"
import useIsDirty from "../../hooks/useIsDirty"
const CustomCodeEditor = () => {
const { isDirty, setIsDirty } = useIsDirty()
console.log("isDirty:", isDirty)
return (
<div className="bg-[#1e1e1e] h-full">
<Editor
onChange={(value) => {
updateCode(value || "")
setIsDirty(true) // updating state
}}
/>
</div>
)
}
export default CustomCodeEditor
EditorFooter
import Button from "../reusable/Button"
const EditorFooter = () => {
const { setIsDirty } = useIsDirty()
const handleSave = async () => {
setIsDirty(false)
}
return (
<div>
<Button
onClick={handleSave}
>
Save
</Button>
<Button
onClick={handleSave}
>
Submit
</Button>
</div>
)
}
export default EditorFooter
Hooks are not singleton instances.. when you use useIsDirty somewhere.. it always create new instance, with unrelated states to other ones. If you want to share this state you need to use Context
const IsDirtyContext = createContext(undefined);
const IsDirtyProvider = ({ children }): ReactElement => {
const [isDirty, setIsDirty] = useState(false)
return <IsDirtyContext.Provider value={{isDirty, setIsDirty}}>{children}</IsDirtyContext.Provider>;
};
and then you should wrap your commponent tree where you wanna access it with IsDirtyProvider
after that, you can even create your custom hook that will just return that context:
const useIsDirty = () => {
return useContext(IsDirtyContext)
}
Looking at your question, it looks like you are trying to use the same state in both components. However, the state doesn't work like that. A new instance is created whenever you make a call to useIsDirty from a different component.
If you want to use the state value across two components. You can do that using one of the following ways.
1 - Use a parent and child hierarchy.
Steps
Create a parent component and wrap the two components inside the parent component.
Manage the state in the parent component and pass it using props to the child component.
Create a function in child components that will execute a function from the parent component. The parent component function will hold the code to update the state based on whatever value you receive from the child component.
Now you should be able to share your state between both components.
2 - Use the context api.
If you are not familiar with what context api is, below is a brief explanation.
Context api helps you share data between components, without the need of passing them as a prop to each and every component.
You can use createContext and useContext hooks from context api.
createContext is used to create a new context provider.
useContext hook is used to manage the state globally.
You can get the value from context using this function.
Whenever the state is updated the value will be reflected globally.
Note - Any component that needs to use the value inside the useContext should be wrapped inside the useContext provider component.
Steps to create a context provider.
To create a context you just need to use the react hook createContext
Create a context using below code
const isDirtyContext = createContext();
Wrap your components in the context provider
import {IsDirtyContext} from './path/filename'
<IsDirtyContext.Provider value={[isDirty, setIsDirty]}>{children}</IsDirtyContext.Provider>
If your context is in a separate file, then you can import it into any child component using the import statement.
import {IsDirtyContext} from './path/filename'
Use the context
const [isDirty] = useContext(IsDirtyContext);
Now the isDirty state value is available globally in all components.
Hope this information helps you. Please upvote if this helps you understand and solve the problem.

React - call function in child component if parent state changes

I've got an invisible fullscreen event processing component that catches and processes all mouse events. On certain events I want to call a particular function in a child component. I created a state variable in the parent component. I am listening with use effect in the child component if there are some changes to the state variable in the parent component. However the effect hook is being called to often. Is there a better way of doing this? In particular I want to set drawing=true on mouse down and drawing=false on mouse up. If drawing transitions from true to false I want so save something in the database. Therefore it's important that the function in useState is being called only once.
I have these two possible solutions.
If you want useEffect not to be called in the first render, you have to use a custom hook, probably called useUpdateEffect. Here is a usage guide from react-use package
use useImperativeHandle to run a function in child from parent.
example:
import React, { forwardRef, useRef } from 'react';
export default function Parent() {
const ref = useRef<Ref>(null!);
const handleCallFunction = (): void => ref?.current?.functionInChild();
return (
<div>
<button onClick={handleCallFunction}>
call a function in child from parent
</button>
<Child ref={ref} />
</div>
);
}
type Ref = {
functionInChild: () => void;
};
type Props = {};
const Child = forwardRef<Ref, Props>((props, ref) => {
const functionInChild = () => {
console.log('called from parent');
};
React.useImperativeHandle(ref, () => ({ functionInChild }));
return <div>Child!</div>;
});
You have to put this in your code
useEffect(()=>{
/*Query logic*/
console.log('i fire once');},[your_variable]);
you_variable which you want to change when this variable changes his value

Convert class component to functional components using hooks

I am trying to convert this class component to functional component using hooks
import React, { Component, cloneElement } from 'react';
class Dialog extends Component {
constructor(props) {
super(props);
this.id = uuid();
}
render(){
return ( <div>Hello Dialog</div> );
}
}
This component is initiated with a specific ID because I may have to use multiple instances of them. How can I achieve this if I use functional component?
One solution would be to use useEffect to create your ID at the first render, and store it in the state :
const Dialog = () => {
const [id, setId] = useState(null);
useEffect(() => {
setId(uuid())
}, [])
return <div>Hello Dialog</div>
}
Giving an empty array as the second parameter of useEffect makes it unable to trigger more than once.
But another extremely simple solution could be to just... create it outside of your component :
const id = uuid();
const Dialog = () => {
return <div>Hello Dialog</div>
}
You may store it in state:
const [id] = useState(uuid()); // uuid will be called in every render but only the first one will be used for initiation
// or using lazy initial state
const [id] = useState(() => uuid()); // uuid will only be called once for initiation
You may also store it in React ref:
const id = useRef(null);
if(!id.current) {
// initialise
id.current = uuid();
}
// To access it’s value
console.log(id.current);
Any instance property becomes a ref pretty much, and you would access idRef.current in this case for the id
function Dialog() {
const idRef = useRef(uuid())
return <div>Hello Dialog</div>
}
Thank you all, your solutions works well. I also try this solution and I find it OK too: replace this.id with Dialog.id. Is there any downside with this solution?

current is always null when using React.createRef

I was trying to do this.
I must be missing something, but I don't understand why current is always null in this example.
class App extends React.PureComponent {
constructor(props) {
super(props);
this.test = React.createRef();
}
render() {
return <div className="App">current value : {this.test.current + ""}</div>;
}
}
You can check my test case here
Because you forgot to assign the ref to some dom element. You are only creating it.
Write it like this:
class App extends React.PureComponent {
constructor(props) {
super(props);
this.test = React.createRef();
}
handleClick = () => alert(this.test.current.value)
render() {
return (
<div className="App">
<input ref={this.test} />
<button onClick={this.handleClick}>Get Value</button>
</div>
)
}
}
Working Example.
I know this is not the solution to OP's problem but for those who are coming from google search, one of the ways the ref.current can be null is that if the component on which the ref is being attached is a connected component. Like with react-redux connect or withRouter. For react-redux the solution is to pass forwardRef:true in the fourth option to connect.
React.createRef() is asynchronous so if you try to access the ref in componentDidMount, it will return null and later return the properties of the component in which you are referencing.
componentDidMount(): void {
if (this.viewShot && this.viewShot.current) {
this.viewShot.current.capture().then((uri) => {
console.log('do something with ', uri);
});
}
}
This is the right way to use the React.createRef() in this context.
You're missing the ref={this.test} prop.
return (
<div className="App" ref={this.test}>
current value : {this.test.current + ""}
</div>
);
This may happen in the following circumstances:
You have forgotten to pass your ref to the component i.e this.test from the question.
<Component ref={this.test} />
You are using Redux in which the component to which ref props is passed is wrapped by connect method and hence this.test.current would return null as it points to the Redux wrapper, to make this kind of component work make forwardRef: true
i.e: connect(mapStateToProps, mapDispatchToProps, null, {forwardRef: true})(Component)
If you are using withRouter and connect together then instead of one here you are having two wrappers and this.test.current would obviously return null, to overcome this make sure withRouter wraps connect
withRouter(connect(mapStateToProps, mapDispatchToProps, null, {forwardRef: true})(Component))
and then
<Component wrappedComponentRef={ref => this.test = ref} />
wrappedComponentRef is a prop used to make the wrapped component available just as forwardRef: true, you can find it in docs here
In version 17.0.2 of React, refs and it being asynchronous got changed. Code like this stopped working properly after the update:
import {useRef} from 'react';
import './kind.css'
const Kind = ({prop}) => {
// defining the ref
const kindRef = useRef('')
// print the ref to the console
console.log(kindRef)
return (
<div ref={kindRef} className="kind-container" >
<div className="kind" data-kind='drink'>Drink</div>
<div className="kind" data-kind='sweet'>Sweet</div>
<div className="kind" data-kind='lorem'>lorem</div>
<div className="kind" data-kind='ipsum'>ipsum</div>
<div className="kind" data-kind='ipsum' >food</div>
</div>
);
}
export default Kind;
After initializing the ref it takes sometime to assign it to the dom. Javascript, being a synchronous language, doesn't wait for the ref to initialize and skips straight to the log.
To fix this we will need to use useEffect like this
import { useRef, useEffect} from 'react';
import './kind.css'
const Kind = ({prop}) => {
// defining the ref
const kindRef = useRef('')
// using 'useEffect' will help us to do what ever you want to your ref varaible,
// by waiting to letting the elements to mount:'mount means after the elements get inserted in the page' and then do what you want the ref
useEffect(()=>{
// print the ref to the console
console.log(kindRef)
})
return (
<div ref={kindRef} className="kind-container" >
<div className="kind" data-kind='drink'>Drink</div>
<div className="kind" data-kind='sweet'>Sweet</div>
<div className="kind" data-kind='lorem'>lorem</div>
<div className="kind" data-kind='ipsum'>ipsum</div>
<div className="kind" data-kind='ipsum' >food</div>
</div>
);
}
export default Kind;
useEffect waits to the ref to be assigned to the DOM element and then runs the function assigned to it.
If you are using the ref in useCallback (or another hook), remember to add the ref to the dependencies:
const doSomething = useCallback(() => {
ref.current?.doIt();
}, [ref]);
<div ref={this.test}>
You have to assign ref prop to your DOM element.
In this case you have to assign ref to div element

Understanding React Higher-Order Components

Can someone please explain Higher-order components in React. I have read and re-read the documentation but cannot seem to get a better understanding. According to the documentation, HOCs help remove duplication by creating a primary function that returns a react component, by passing arguments to that function.
I have a few questions on that.
If HOCs create a new enhanced component, can it be possible not to pass in any component as argument at all?
In an example such as this, which is the higher order component, the Button or the EnhancedButton.
I tried creating one HOC like this:
// createSetup.js
import React from 'react';
export default function createSetup(options) {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.testFunction = this.testFunction.bind(this);
}
testFunction() {
console.log("This is a test function");
}
render() {
return <p>{options.name}</p>
}
}
}
// main.js
import React from 'react';
import {render} from 'react-dom';
import createSetup from './createSetup';
render((<div>{() => createSetup({name: 'name'})}</div>),
document.getElementById('root'););
Running this does not show the HOC, only the div
Can anyone help out with a better example than the ones given?
A HOC is a function that takes a Component as one of its parameters and enhances that component in some way.
If HOCs create a new enhanced component, can it be possible not to pass in any component as argument at all?
Nope, then it wouldn't be a HOC, because one of the conditions is that they take a component as one of the arguments and they return a new Component that has some added functionality.
In an example such as this, which is the higher order component, the Button or the EnhancedButton.
EnhanceButton is the HOC and FinalButton is the enhanced component.
I tried creating one HOC like this: ... Running this does not show the HOC, only the div
That's because your createSetup function is not a HOC... It's a function that returns a component, yes, but it does not take a component as an argument in order to enhance it.
Let's see an example of a basic HOC:
const renderWhen = (condition, Component) =>
props => condition(props)
? <Component {...props} />
: null
);
And you could use it like this:
const EnhancedLink = renderWhen(({invisible}) => !invisible, 'a');
Now your EnhancedLink will be like a a component but if you pass the property invisible set to true it won't render... So we have enhanced the default behaviour of the a component and you could do that with any other component.
In many cases HOC functions are curried and the Component arg goes last... Like this:
const renderWhen = condition => Component =>
props => condition(props)
? <Component {...props} />
: null
);
Like the connect function of react-redux... That makes composition easier. Have a look at recompose.
In short, If you assume functions are analogues to Components, Closure is analogous to HOC.
Try your createSetup.js with:
const createSetup = options => <p>{options.name}</p>;
and your main.js
const comp = createSetup({ name: 'name' });
render((<div>{comp}</div>),
document.getElementById('root'));
A higher-order component (HOC) is an advanced technique in React for reusing component logic. Concretely, a higher-order component is a function that takes a component and returns a new component.
A HOC is a pure function with zero side-effects.
Example: CONDITIONALLY RENDER COMPONENTS
Suppose we have a component that needs to be rendered only when a user is authenticated — it is a protected component. We can create a HOC named WithAuth() to wrap that protected component, and then do a check in the HOC that will render only that particular component if the user has been authenticated.
A basic withAuth() HOC, according to the example above, can be written as follows:
// withAuth.js
import React from "react";
export function withAuth(Component) {
return class AuthenticatedComponent extends React.Component {
isAuthenticated() {
return this.props.isAuthenticated;
}
/**
* Render
*/
render() {
const loginErrorMessage = (
<div>
Please login in order to view this part of the application.
</div>
);
return (
<div>
{ this.isAuthenticated === true ? <Component {...this.props} /> : loginErrorMessage }
</div>
);
}
};
}
export default withAuth;
The code above is a HOC named withAuth. It basically takes a component and returns a new component, named AuthenticatedComponent, that checks whether the user is authenticated. If the user is not authenticated, it returns the loginErrorMessage component; if the user is authenticated, it returns the wrapped component.
Note: this.props.isAuthenticated has to be set from your application’s
logic. (Or else use react-redux to retrieve it from the global state.)
To make use of our HOC in a protected component, we’d use it like so:
// MyProtectedComponent.js
import React from "react";
import {withAuth} from "./withAuth.js";
export class MyProectedComponent extends React.Component {
/**
* Render
*/
render() {
return (
<div>
This is only viewable by authenticated users.
</div>
);
}
}
// Now wrap MyPrivateComponent with the requireAuthentication function
export default withAuth(MyPrivateComponent);
Here, we create a component that is viewable only by users who are authenticated. We wrap that component in our withAuth HOC to protect the component from users who are not authenticated.
Source
// HIGHER ORDER COMPOENTS IN REACT
// Higher order components are JavaScript functions used for adding
// additional functionalities to the existing component.
// file 1: hoc.js (will write our higher order component logic) -- code start -->
const messageCheckHOC = (OriginalComponent) => {
// OriginalComponent is component passed to HOC
const NewComponent = (props) => {
// business logic of HOC
if (!props.isAllowedToView) {
return <b> Not Allowed To View The MSG </b>;
}
// here we can pass the props to component
return <OriginalComponent {...props} />;
};
// returning new Component with updated Props and UI
return NewComponent;
};
export default messageCheckHOC;
// file 1: hoc.js -- code end -->
// file 2: message.js -- code start -->
// this is the basic component we are wrapping with HOC
// to check the permission isAllowedToView msg if not display fallback UI
import messageCheckHOC from "./hoc";
const MSG = ({ name, msg }) => {
return (
<h3>
{name} - {msg}
</h3>
);
};
export default messageCheckHOC(MSG);
// file 2: message.js -- code end -->
// file 3 : App.js -- code start --->
import MSG from "./message.js";
export default function App() {
return (
<div className="App">
<h3>HOC COMPONENTS </h3>
<MSG name="Mac" msg="Heyy !!! " isAllowedToView={true} />
<MSG name="Robin" msg="Hello ! " isAllowedToView={true} />
<MSG name="Eyann" msg="How are you" isAllowedToView={false} />
</div>
);
}
// file 3 : App.js -- code end --->

Categories

Resources