React JS doesn't render after function is done - javascript

const handleMenu = async () => {
let menu = await document.querySelector('.navbar-list');
menu.classList.toggle('.navbar-list-active');
}
return (
<div className="navbar-list">
<div onClick={handleMenu} className="hamburger">
</div>
</div>
)
The thing is that after class is added to component it really added on the element, but the CSS styling doesn't appear on the element with added class, is this something React is doing? How can I force CSS to re-render the page?

await doesn't do anything useful unless the value you are awaiting is a promise. querySelector returns either null or an element: never a promise. Your code won't wait for the element to exist.
Now, you can use useRef to get a reference to the element which would then let you toggle the class on it… but don't.
The React way to solve this problem is to store the toggled state in the state and deal with it in the JSX.
const MyComponent = () => {
const [active, setActive] = useState(false);
const classNames = ["navbar-list"];
if (active) classNames.push("navbar-list-active");
const handleMenu = () => setActive(!active);
return (
<div className={classNames}>
<button onClick={handleMenu} className="hamburger">
Toggle Menu
</button>
</div>
;)
}
Note that I've changed the div to a button. This is an important accessibility feature and allows the menu to be activated by people who don't use a pointing device to access a page. There is more you should do for accessibility and this article is a good starting point (although it uses traditional DOM instead of React so you'll need to adapt it to use state as I did here).

Related

onClick not working when I attempt to change value of variable

In React, I'm attempting to change the display of 2 elements when certain buttons are clicked on. I either want the title displayed, or an input to edit the title. My title div has a className of a variable named 'titleDisplay' with the value of 'isDisplayed'. I have a function set up to switch it to 'notDisplayed'
let titleDisplay = 'isDisplayed';
let editDisplay = 'notDisplayed';
const editDisplayed = () => {
editDisplay = 'isDisplayed'
titleDisplay = 'notDisplayed'
}
<button onClick={editDisplayed} id="edit-btn">EDIT</button>
<div className={titleDisplay}>
<h2 className='indieNotebookTitle'>{notebook?.title}</h2>
</div>
.isDisplayed {
display: block;
}
.notDisplayed {
display: none;
}
Not sure what I'm doing wrong since onClick has been working with functions up until now.
React will only re-render a component in response to a state change. Reassigning a variable, by itself, almost never has any side-effects, unless the variable is used later. Your reassignment of editDisplay would only be visible to other functions within the same component binding (a very unusual occurrence to see in React, and usually an indicator of a logic problem).
You need to make the variables you try to change stateful instead. Also, consider using a boolean value rather than a string value. You may be able to use only a single state value instead, to toggle between the title and the edit.
const [editingTitle, setEditingTitle] = useState(false);
<button onClick={() => setEditingTitle(false)} id="edit-btn">EDIT</button>
<div className={editingTitle ? 'isDisplayed' : 'notDisplayed'}>
<h2 className='indieNotebookTitle'>{notebook?.title}</h2>
</div>

how to add attribute without actually editing the HTML element in react

I have a below HTML component created in REACT which I cant edit directly. But I need to add one attribute to one of its HTML element. I can't use jquery as well other wise its easy to do with jQuery.
Below is the base HTML for table which I cant edit directly but I can just use this component in my code.
Challenge : I need to add attribute to the SVG element. e.g. -> data-id="1". Can it be done with CSS or any other way.
<TablePresenter>
<div>
<svg>this is a actually a sort button</svg>
<div>Column 1 Name</div>
</div>
<div>
<svg>this is a actually a sort button</svg>
<div>Column 2 Name</div>
</div>
</TablePresenter>
main file which I can edit is as below.
const MyComponent = () => {
some logic here...
Can we do something here may be CSS or any react hack to get underline component HTML change.
return(
<TablePresenter></TablePresenter>
)
}
export default MyComponent;
Not a recommended way of doing, but using a ref you can achieve this, a sample below:
Add a wrapper div to your parent component (your own component which can be edited) like below and add a ref to it, that will helps you to get the DOM reference of the html inside the <TablePresenter>
const divRef= useRef<HTMLDivElement>(null);
return <div ref={divRef}>
<TablePresenter></TablePresenter>
</div>
// This is an example of getting the reference of the svg.
divRef.current.firstElementChild.firstElementChild.firstElementChild
May be something like this:
const MyComponent = () => {
const divRef = useRef<HTMLDivElement>(null);
useEffect(()=>{
divRef.current.firstElementChild.firstElementChild.firstElementChild.attributes["data-id"]=1
}, [])
return <div ref={divRef}>
<TablePresenter></TablePresenter>
<SuperChild />
</div>
}

How to send a usestate through props with interface in TypeScrips and react?

I'm trying to make a light / dark theme . And I have 2 components.
The first component is the one below. I succeeded to make a boolean to change my style in my component. It was good so far :
export interface Props{
theme:boolean;
}
const Theme: FC<Props> = ({theme}) => {
const [light,setLightMode]=useState(false);
return (
<div>
<div className="card__theme">
<div className={light ? "card__light" : "card__light--active"}>Light</div>
<Switch inputProps={{ "aria-label": "controlled" }} onChange={()=>setLightMode(!light)}/>
<div className={ light ? "card__Dark" : "card__Dark--active"}>Dark</div>
</div>
</div>
);
};
What I do right now is to use this component in my Home page where I want to do the same thing.
I want to change the style of my components , making 2 className like the code above with a boolean state.
The problem that I'm facing is that I can't make another function onChange={} in my home component. First I don't send in interface a function . I want my const [light,setLightMode]=useState(false); and my function onChange={()=>setLightMode(!light)} when I switch the button to work in my Home component from below
const Home: FC = () => {
const percentage = 91;
const [dark,setDark] = useState(false);
return (
<div>2
<div className="Container-body">
<div className="card">
<div className={dark ? "card__theme" : "card__theme--active"}>
<Theme theme={dark} onChange={()=>{setDark(!dark)}}/>
</div>
So to make it sort. I want to use just the light, setlightTheme boolean state from my Theme component in my Home component . I don't know how I can send this with props in TypeScript...
Here is a print with my code : enter link description here
I'm not sure if I understand correctly, but I think your goal is to pass the onChange function to the Theme component from the parent component.
If so, I hope this snippet can help you. Basically I added the onChange parameter in the interface as a function. I also renamed the theme parameter to dark.
To make the two components work together, I removed the useState in the Theme component and used the dark variable (taken from the parent component) to manage the styles.
export interface Props {
dark: boolean;
onChange?: () => void;
}
const Theme: FC<Props> = ({ dark, onChange }) => {
return (
<div>
<div className="card__theme">
<div className={dark ? 'card__light' : 'card__light--active'}>
Light
</div>
<Switch
inputProps={{ 'aria-label': 'controlled' }}
onChange={onChange}
/>
<div className={!dark ? 'card__Dark' : 'card__Dark--active'}>Dark</div>
</div>
</div>
);
};
So if I understand correctly you just want to provide an option for switching light and dark mode. From an architectural point of view you don't want to do this on a component-level since multiple component might need to change.
BEM Mistake
Before I address a proper solution you are currently making a BEM mistake with this line:
<div className={dark ? 'card__light' : 'card__light--active'}>
A modifier --modifier can only live together with an actual element card. So on a fully outputted HTML this is valid card__light card__light--active but in your example either card__light or card__light--active is being rendered.
Solution for theme switching
When it comes down to switching a dark/light theme you either want to make this value (true or false) available in a centralised state by using something like Redux or you might want to declare it on your root component (most often the <App />) and start using it from there.
I don't recommend prop drilling for this use case since it will make your code messy in the long run. This is a really nice use case for the Context API.
✅ See working example Playground.
P.s. I use Typescript for better code, you can ignore the syntax you don't know.
React documentation
The React documentation has an exact example for you see docs theme switching.

How to perform a click on element2 when element1 is clicked in React js?

I have two independent elements (not a parent-child).
Is it possible to accomplish the behavior such that StyledDropDownInputAsync is actually clicked on clicking StyledSearchInput.
<StyledSearchInput/>
<StyledDropdownInputAsync searchIcon
className="options"
placeholder="Search"
loadOptions={loadOptions}
onChange={this.handleSelection}
cache={{}}
filterOptions={(options) => (options)}>
</StyledDropdownInputAsync>
Wrap them in a parent component, define a click state, pass the click state to StyledDropdownInputAsync, pass the click action to StyledSearchInput.
const ParentComp = () => {
const [isClicked, setClick] = useState(false);
return (
<>
<StyledSearchInput onClick={() => setClick(true)}/>
<StyledDropdownInputAsync isClicked={isClicked} {...otherProps}>
</StyledDropdownInputAsync>
</>
);
};
This called Lifting State Up in ReactJS.
You can use ref to implement such things,
according to documentation, Refs provide a way to access DOM nodes or React elements created in the render method.
you can read more about refs using this link.
for implementing such functionality, please refer to this code sandbox

React replace event.target with input

UPDATE
Here's are some demos
contentEditable demo - requires double click for H1 to become editable
replace with input demo - adopts event.target styles but makes the UI 'twitch' when rendered
So I have some functional components, let's say:
component1.js
import React from 'react';
const component1 = props => (
<div>
<h1>Title</h1>
</div>
);
export { component1 };
They are variable. event.target could be anything with text, so paragraph, heading, anything. I'm trying to let users edit content inline by clicking on it, so I'll pass a function editMode to these functional components, that'll update parent state with editing info, let's say like this:
<h1 onClick={event => {editMode(event, props.name, props.title, 'title')}}>title</h1>
This changes parent local state to have all the necessary information to grab the value from redux, define a target etc. For this example, props.name is the name of the component, props.title is the value, and 'title' is object key in redux.
So I'll add something to my component1.js and make it look a bit like this:
import React from 'react';
const component1 = props => (
<div>
{props.editState === 'true' &&
<EditLayout
name={props.name}
target={props.target}
value={props.value}
onChange={event => someFunc(event)}
/>
}
<h1>Title</h1>
</div>
);
export { component1 };
Now this works fine, except it doesn't scale. EditLayout, in this case, will just return an input with correct value. What I need it to do is to adapt to whatever is being clicked, get font size, background, padding, margin, position. Am I doing this right? Every way I try, I run into huge issues:
Idea 1 - move EditLayout component outside of the functional component
Issue: positioning
So I'll move EditLayout to parent component that contains both component1.js and EditLayout. This will allow me to manipulate it from inside the functional component, without having to include it everywhere. I'll then grab coordinates and other important information from event.target like so:
const coords = event.target.getBoundingClientRect();
const offsetX = coords.left;
const offsetY = coords.top;
const childHeight = coords.height;
const childWidth = coords.width;
const childClass = event.target.className;
I'll then wrap the EditLayout to return a container which contains an input, and apply size/coordinates to the absolutely positioned container. This'll present an issue of input being offset by a random amount of pixels, depending on how big/where is the event.target.
Idea 2 - pass relevant computed styles to EditLayout
Issue: twitching on render, and I have to add EditLayout for every possible event.target there is, as well as condition its' render
So I'll grab all important computed styles like this:
const computedTarget = window.getComputedStyle(event.target);
const childMargins = computedTarget.marginBottom;
const childPaddings = computedTarget.padding;
const childFontSize = computedTarget.fontSize;
const childTextAlign = computedTarget.textAlign;
And pass it to component1.js, and then pass it to EditLayout component inside the component1.js. I'll then condition theevent.target to hide if it's being edited like this:
<h1 className={ props.target === 'title' ? 'd-none' : ''}>Title</h1>
And condition the EditLayout to show only if it's needed:
{props.target === 'title' && <EditLayout />}
In this example, clicking h1 will show the input, but the layout itself with twitch on render. Input will have the exact same margin and font size as the h1, or event.target, but it'll appear bigger and extend the layout. Demo:
Idea 3 - Use conditional contentEditable
Issue: Requires double click to enable, doesn't work in safari, doesn't let me preselect the value
This is the weirdest of them all. I figured it'd be pretty simple, do something like this inside the functional component render:
<h1 contentEditable={props.target === 'title'} onClick={event => props.setTarget(event)}>Title</h1>
However, I have to double click to enable it. I have no idea why, if I attach a console log every time onClick is fired, I'll get correct outputs, I'll get the correct target value as well. I've tried numerous ways, but it simply requires double click. Even attempted to handle this inside the functional component, as most of the stuff is handled by a parent component, doesn't make a difference.
I have oversimplified the examples, so it's safe to assume/understand the following:
I am passing props in a correct fashion, they aren't undefined
I am using bootstrap
I am using styled components, and EditLayout is a styled component
which accepts props and turns them into CSS like: font-size: ${props
=> props.fontSize};
The values should be correct, I am not manipulating anything I get back from getComputedStyle() or getBoundingClientRect()
I am keen on keeping my functional components functional, and easy to
add. Functional components, in this case, are simple HTML structures,
and I'd like to keep them as simple as possible
So there's a neat solution to contentEditable requiring two clicks instead of one, instead of binding onClick and passing it to enable contentEditable, simply keep contentEditable true and handle the change however you like. Here's a working h1 that doesn't require two clicks to enable contentEditable, unlike the one in the demo
<h1
className="display-4 text-center"
contentEditable
suppressContentEditableWarning
onBlur={event => updateValues(event)}
>
Title
</h1>
The available methods for trigger update could be onBlur or onInput.

Categories