Want to render different component after click on Add Button - javascript

I want to render VehicleInfoRender.js when click on 'Add' button which is in UMUIMAdditionalCoverage.js
App.js
import './App.css';
const App = () => {
return (
<BasicLayout />
);
}
export default App;

First add a state to manage toggling VehicleInfoRender
state = { activeIndex: 0, showVehicleInfo: false}
Then add a function to toggle showing and hiding the component
<Button onClick={this.toggleVehicleInfo}>Add</Button>
const toggleVehicleInfo = () => {
this.setState((prevState) => {showVehicleInfo: !prevState.showVehicleInfo});
};
Finally add this where you want to render the component
{this.state.showVehicleInfo && <VehicleInfoRender />}

Use state (eg: isShowVehicleInfoRender) to handle turn on/off render this component

Related

Can't update parent component state with React UseState

im facing this weird behavior when trying to update the parent component with an set function to the child with props
this hook is to open and close the modal to edit an element
//PARENT FILE
//hook
const [isEditModalOpen, setEditModalOpen] = useState(false)
//more code...
//modal
{isEditModalOpen && <EditExcerciseModal setEditModalOpen={setEditModalOpen} isEditModalOpen={isEditModalOpen} />}
and this is the child code
//CHILD FILE
export const EditExcerciseModal = ({setEditModalOpen, excerciseInfo,fetchExcercisesFromRoutine})
//more code etc etc
<div className="addExcerciseModalContainer">
<span onClick={() =>{ setEditModalOpen(false) }} className="xModal">X</span>
i checked and the onClick is working. if i change the parent state manually the Modal works fine and closes.
the weird case when it its working is when instead of calling the set function i create a function with a setTimeout without time like this:
function closeModal(){
setTimeout(() => { setEditModalOpen(false)}, 0);
}
any ideas?
thanks for the help
You need to create a separation of concern. A Modal consists of three parts
The Modal of its Self.
The Content of the Modal.
And the container of the two.
You should be using the useState() hook and calling setEditModalOpen in the same containing component.
You need to make sure that you're declaring and setting state inside the same component.
// children would be the content of the modal
const Modal = ({ children, selector, open, setOpen }) => {
// we need the useEffect hook so that when we change open to false
// the modal component will re-render and the portal will not be created
useEffect(() => {
setOpen(false);
//provide useEffect hook with clean up.
return () => setOpen(true);
}, [selector]);
return open ? createPortal(children, selector) : null;
};
export const EditExerciseModal = ({ close }) => {
return (
<div>
{/* Instead of creating a handler inside this component we can create it in it's parent element */}
<span onClick={close}>X</span>
{/* Content */}
</div>
);
};
export const ModalBtn = () => {
const [isEditModalOpen, setEditModalOpen] = useState(false);
// this is where it all comes together,
// our button element will keep track of the isEditModalOpen variable,
// which in turn will update both child elements
// when true useEffect hook will re-render Modal Component only now it "will" createPortal()
// when our EditExerciseModal alls close it will set change the isEditModalOpen to false
// which will be passed to the Modal component which
// will then cause the component to re-render and not call createPortal()
return (
<>
<button onClick={() => setEditModalOpen(true)}>EditExerciseModal</button>
{setEditModalOpen && (
<Modal
open={isEditModalOpen}
setOpen={setEditModalOpen}
selector={'#portal'}>
<div className='overlay'>
<EditExerciseModal close={() => setEditModalOpen(false)} />
</div>
</Modal>
)}
</>
);
};

React / Functional component / Conditional render on callback / Not Working

Why this does not work ?
import React from 'react';
function Room() {
let check = null;
const ibegyouwork = () => {
check = <button>New button</button>;
}
return (
<div>
<button onClick={ibegyouwork}>Display my button now !!!!</button>
{check}
</div>
);
}
export default Room;
And this works fine ?
import React from 'react';
function Room() {
let check = null;
return (
<div>
<button>No need for this button because in this case the second button is auto-displayed</button>
{check}
</div>
);
}
export default Room;
Basically I try to render a component based on a condition. This is a very basic example. But what I have is very similar. If you wonder why I need to update the check variable inside that function is because in my example I have a callback function there where I receive an ID which I need to use in that new component.
The example that I provided to you is basically a button and I want to show another one when I press on this one.
I am new to React and despite I searched in the past 2 hours for a solution I couldn't find anything to address this issue.
Any tips are highly appreciated !
Your component has no idea that something has changed when you click the button. You will need to use state in order to inform React that a rerender is required:
import React, {useState} from 'react'
function Room() {
const [check, setCheck] = useState(null);
const ibegyouwork = () => {
setCheck(<button>New button</button>);
}
return (
<div>
<button onClick={ibegyouwork}>Display my button now !!!!</button>
{check}
</div>
);
}
export default Room;
When you call setCheck, React basically decides that a rerender is required, and updates the view.
The latter is working because there are no changes to the check value that should appear on the DOM.
If check changes should impact and trigger the React render function, you would want to use a state for show/hide condition.
import React from 'react';
const Check = () => <button>New button</button>;
function Room() {
const [show, setShow] = React.useState(false);
const ibegyouwork = () => {
setShow(true);
}
return (
<div>
<button onClick={ibegyouwork}>Display my button now !!!!</button>
{show && <Check />}
</div>
);
}
export default Room;

What is going wrong when I pass a boolean from a child to its parent component using React Hooks?

I'm currently trying to revise the dropdown menu component on my Gatsby site so that it reports a boolean to its parent component, a navbar. I plan on using that boolean to trigger some conditional CSS in Emotion.
The boolean isOpen reports if the dropdown menu is open or not, so true means it's open, and false means it's not.
As of now, I'm using React Hooks to pass that data from the child to the parent component. It seems like I'm successfully passing data, but when I click the dropdown menu, it sends both a true and a false boolean value in rapid succession, even as the menu remains open.
How do I revise this code so that isOpen in the child component is correctly reported to the parent component?
import React, { useState, useEffect } from "react"
const Child = ({ isExpanded }) => {
const [expandState, setExpandState] = useState(false)
useEffect(() => {
setExpandState(isOpen)
isExpanded(expandState)
})
return(
<dropdownWrapper>
<button
{...isExpanded}
/>
{isOpen && (
<Menu>
//menu items go here
</Menu>
)}
</dropdownWrapper>
)
}
const Parent = () => {
const [expandState, setExpandState] = useState(false)
const onExpand = (checkExpand) => {
setExpandState(checkExpand)
}
return(
<Dropdown
isExpanded={onExpand}
onClick={console.log(expandState)}
/>
)
}
Figured this one out myself. Parent needed a useEffect to register the incoming boolean.
Fixed code for the parent:
const Parent = () => {
const [expandState, setExpandState] = useState(false)
const onExpand = (checkExpand) => {
setExpandState(checkExpand)
}
useEffect(() => {
onExpand(expandState)
})
return(
<Dropdown
isExpanded={onExpand}
onClick={console.log(expandState)}
/>
)
}

onBlur / onClick conflict with CodeMirror2 in React

I have created multiple CodeMirror cells. OnBlur works fine, however if I click run button on the other cell, instead of firing run, it actually triggers onBlur and then I need to click mouse again to trigger run. Ideally both of these events should be fired when run button is clicked.
I have seen that the issue is with the order of precedence for these two events and one of the proposed solutions was to add ref attribute to code mirror like this ref = {cell => this.cell = cell} and then in the other handler which is related to run button do this.cell.focus() or in some similar way.
Unfortunately I am not even able to access ref attribute for CodeMirror2 so I can't test it. I will paste both of these components and any suggestion is appreciated.
To summarize: The issue is that onBlur shadows onClick, so run button needs to be clicked twice. I want to be able to click run button and that both onBlur and handleRunClick fire.
import React, { Component } from "react";
import { Controlled as CodeMirror } from "react-codemirror2";
import CellResults from "./CellResults";
import CellToolbar from "../Shared/CellToolbar";
import AddCellButton from "../Shared/AddCellButton";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/darcula.css";
import "codemirror/mode/javascript/javascript.js";
import "codemirror/mode/ruby/ruby.js";
import "codemirror/mode/python/python.js";
class CodeCell extends Component {
state = {
code: this.props.cell.code
};
handleChange = value => {
this.setState({ code: value });
};
handleBlur = () => {
this.props.onUpdateCodeState(this.state.code, this.props.cellIndex);
if (this.props.language === "Markdown") {
this.props.toggleRender(this.props.cellIndex);
}
};
render() {
const cell = this.props.cell;
const cellOptions = {
mode: cell.type.toLowerCase(),
theme: "darcula",
lineNumbers: true,
showCursorWhenSelecting: true
};
return (
<div>
<div className="add-cell-container">
<AddCellButton
className="add-cell-btn"
onClick={this.props.onAddClick}
cellIndex={this.props.cellIndex}
/>
</div>
<CellToolbar
cellIndex={this.props.cellIndex}
onDeleteClick={this.props.onDeleteClick}
language={cell.type}
onLanguageChange={this.props.onLanguageChange}
rendered={cell.rendered}
onRunClick={this.props.onRunClick}
/>
<CodeMirror
value={this.state.code}
options={cellOptions}
onBeforeChange={(editor, data, value) => {
this.handleChange(value);
}}
onBlur={this.handleBlur}
/>
{cell.type !== "Markdown" ? (
<CellResults language={cell.type} results={cell.results} />
) : null}
</div>
);
}
}
export default CodeCell;
import React from "react";
import Button from "react-bootstrap/Button";
class RunCellButton extends React.Component {
handleRunClick = () => {
this.props.onClick(this.props.cellIndex);
};
render () {
return (
<Button
className="run-button"
onClick={this.handleRunClick}
variant="secondary"
size="sm"
>
<span>►</span>
</Button>
);
}
};
export default RunCellButton;
Below is the similar problem with Adding Cell. When I trigger click event it fires, the state of show is changed to true but if I log it on line 36 it is still false. I am triggering click event from a different component, again due to this obBlue shadowing everything else so every button needs to be clicked twice.
import React, { Component } from "react";
import SplitButton from "react-bootstrap/SplitButton";
import * as constants from "../../Constants/constants";
import DropdownButton from "react-bootstrap/DropdownButton";
import Dropdown from "react-bootstrap/Dropdown";
class AddCellButton extends Component {
state = {
show: false
}
handleSelectCellType = language => {
this.props.onClick(this.props.cellIndex, language);
};
handleToggle = () => {
this.setState((prevState) => {
return {
show: !prevState["show"]
}
})
}
render() {
const dropDownItems = constants.LANGUAGES.map(language => {
return (
<Dropdown.Item
as="button"
value={language}
key={language}
eventKey={language}
>
{language}
</Dropdown.Item>
);
});
console.log("state of show " + this.state.show)
return (
<DropdownButton
show={this.state.show}
onToggle={this.handleToggle}
className="add-cell-btn"
variant="secondary"
id="dropdown-basic-button"
title={<span>+</span>}
size="sm"
onSelect={this.handleSelectCellType}
>
{dropDownItems}
</DropdownButton>
);
}
}
export default AddCellButton;

Nuka-carousel react move to certain slide

I've got a question about npm package 'nuka-carousel. How to perform goToSlide on clicked element. I have list of elements with scroll3d setting. If I click on e.g last visible element I would like to scroll carousel so that element would be in a center.
According to their GitHub documentation, you can take control of the carousel just by adding onClick to your control button and then use setState() to change the slideIndex:
import React from 'react';
import Carousel from 'nuka-carousel';
export default class extends React.Component {
state = {
slideIndex: 0
};
render() {
return (
<Carousel
slideIndex={this.state.slideIndex}
afterSlide={slideIndex => this.setState({ slideIndex })}
>
...
</Carousel>
<button onClick={(event) => this.handlesClick(event, index)}> />
);
}
handleClick = (event, index) => {
event.preventDefault();
this.setState({slideIndex: index});
}
}

Categories

Resources