how to close react dropdown componet after out focus? - reactjs

I've created a react dropdown component to show a list of data. this data get from server and I handle dropdown list show/hide with display property.
I want to use this component in other components. I need that closed after click out of component in the parent.
export default class Dropdown extends React.Component {
constructor(props) {
super(props);
this.state = {
show: false,
value: "",
data: []
};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.getData();
}
async getData() {
const response = await fetch(this.props.url);
const data = await response.json();
this.setState({ data: data });
}
handleChange(event) {
this.setState({ value: event.target.value });
}
render() {
return (
<div className={styles.container}>
<input type="text" name="name"
onClick={() => this.setState({ show: !this.state.show })}
className={styles.bottonStyle}
value={this.state.value}
onChange={this.handleChange}
/>
<div style={Object.assign({
position: "absolute", backgroundColor: "#f9f9f9", minWidth: "350px", zIndex: "1"
}, this.state.show ? { display: "block" } : { display: "none" })} >
<div style={Object.assign({ backgroundColor: "lightgray" }, !this.state.showMounthList ? { display: "block" } : { display: "none" })} >
<table>
<tr style={{ backgroundColor: "orange" }}>
<th>Id</th>
<th>code</th>
<th>name</th>
</tr>
{
this.state.data.length > 0 ? (
this.state.data.map((item) => {
return <tr>
<td>{item.id}</td>
<td>{item.code}</td>
<td>{item.fullName}</td>
</tr>
})
) : null
}
</table>
</div>
</div >
</div >);
}}

Related

There is two button, once click on the button the name of the button will render inside the id

Hi guys help me on this i am stuck for a project.
After the button click, the page should look like:
Example
Once click on the button the bellow text will call the color name just like the image
class ColorChange extends Component {
constructor(props) {
super(props);
this.state =
}
render() {
return null;
}
}
class App extends Component {
state = {
text: ''
}
onDocumentClick = (event) => {
if (event.target.tagName === 'BUTTON') {
this.setState({ text: event.target.textContent })
}
}
componentDidMount() {
document.addEventListener('click', this.onDocumentClick)
}
componentWillUnmount() {
document.removeEventListener('click', this.onDocumentClick)
}
render() {
return <div>
{this.props.children}
<Tooltip text={this.state.text}/>
</div>
}
}
<button id="btnGreen">Green</button>
<button id="btnRed">Red</button>
document.getElementById("button2").click();
You can use this code:
import { Component } from "react";
export default class App extends Component {
state = {
text: ""
};
render() {
return (
<div className="App">
<button
style={{
backgroundColor: "green",
color: "white",
cursor: "pointer"
}}
onClick={() => this.setState({ text: "GREEN" })}
>
GREEN
</button>
<button
style={{ backgroundColor: "red", color: "white", cursor: "pointer" }}
onClick={() => this.setState({ text: "RED" })}
>
RED
</button>
<br />
COLOR: {this.state.text}
</div>
);
}
}
You can take a look at this sandbox for a live working example.

Create dynamic json based on user input

I have two dropdowns and a couple of images on it what I want is when the user selects the dropdowns and selects image I want to create the JSON format like below:
[data: {
dropdown1:'user input',
dropdown2:'user input',
image url:'url'
}]
my react code:
import React from "react";
import axios from 'axios'
import '../Login.css'
export default class Inference extends React.Component {
constructor(props) {
super(props);
this.state = {
courses: [],
course: "",
inferenceout: [],
model: "",
isLoading: false,
options: [
{ label: "resnet-50torch", value: "resnet-50torch" },
{ label: "densenet_onnx", value: "densenet_onnx" },
{ label: "inception_graphdef", value: "inception_graphdef" },
],
};
this.handleChange = this.handleChange.bind(this);
this.handleChangeCourse = this.handleChangeCourse.bind(this);
this.click = this.click.bind(this);
}
handleChange(e) {
console.log("Model Selected!!");
this.setState({ model: e.target.value });
}
handleChangeCourse = (event) => {
this.setState({ course: event.target.value });
};
getUnique(arr, comp) {
const unique = arr
//store the comparison values in array
.map((e) => e[comp])
// store the keys of the unique objects
.map((e, i, final) => final.indexOf(e) === i && i)
// eliminate the dead keys & store unique objects
.filter((e) => arr[e])
.map((e) => arr[e]);
return unique;
}
click() {
this.setState({ isLoading: true });
axios
.get(
`http://localhost:5000/model-list`
)
.then((res) => {
this.setState({
inferenceout: res.data , isLoading: false,
})
let newWin = window.open("about:blank", "res.data", "width=400,height=400");
newWin.document.write(JSON.stringify(res.data))
localStorage.setItem("apiData", JSON.stringify(res.data));
var data = JSON.parse(localStorage.getItem("apiData"));
console.log(data)
})
}
handleSubmit(event) {
event.preventDefault();
axios.post('http://localhost:5000/getmodel', {
model: this.state.model,
dataset:this.state.course
})
.then((res) => {
// Res.data is the response from your server
localStorage.setItem("apiData1", JSON.stringify(res.data));
});
var data = JSON.parse(localStorage.getItem("apiData1"));
console.log(data)
}
componentDidMount() {
axios
.get(`http://localhost:5000/files`)
.then((response) =>
this.setState(
{
courses: response.data
},
)
)
.catch((err) => console.log(err))
}
render() {
const uniqueCouse = this.getUnique(this.state.courses, "dataset");
const { courses, course, options } = this.state;
const filterDropdown = courses.filter(function (result) {
return result.dataset === course;
});
return (
<div className="container">
<div className="row">
<div
className="col-6"
style={{
paddingBottom: "100px",
paddingTop: "20px",
alignItems: "center",
}}
>
<label
className=""
style={{ paddingTop: "5px", marginTop: "40px" }}
>
Dataset
<form onSubmit={this.handleSubmit.bind(this)}>
<select
className="custom-select"
value={this.state.course}
onChange={this.handleChangeCourse}
style={{ paddingTop: "5px", marginTop: "10px" }}
>
<option>--Select--</option>
{uniqueCouse.map((course) => (
<option key={course.id} value={course.dataset}
onChange={(e) => this.setState({ dataset: e.target.value })}>
{course.dataset}
</option>
))}
</select>
<button
type="submit"
class="btn"
style={{ marginTop: "" }}
>
ok
</button>
</form>
</label>
</div>
<div
className="col-6"
style={{
paddingBottom: "100px",
paddingTop: "20px",
alignItems: "center",
}}
>
<label
className=""
style={{ paddingTop: "5px", marginTop: "40px" }}
>
Model
<form onSubmit={this.handleSubmit.bind(this)}>
<select
className="custom-select"
name="example"
value={this.state.model}
onChange={this.handleChange}
style={{ paddingTop: "5px", marginTop: "10px" }}
>
<option>--Select--</option>
{options.map((option) => (
<option
value={option.value}
onChange={(e) => this.setState({ model: e.target.value })}
>
{option.label}
</option>
))}
</select>
<button
type="submit"
class="btn"
style={{ marginTop: "" }}
>
ok
</button>
</form>
</label>
</div>
{filterDropdown.map((course) => (
<div className="col-2">
<input type="checkbox" id="myCheckbox1" />
<label for="myCheckbox1" className="labell">
<img
key={course.id}
src={`${course.path}`}
height="80"
className="card-img-top img-responsive"
alt="img"
/>
</label>
</div>
))}
<button
type="submit" onClick={this.click} disabled={this.state.isLoading}
class="btn btn-success"
style={{ marginLeft:"45%" ,marginBottom:"10px"}}
>
Inference
</button>
<button
type="submit"
class="btn btn-primary"
style={{ marginLeft:"45%"}} onClick={()=> window.open("/visual", "data","width=400,height=400")}
>
Get Output
</button>
</div>
</div>
);
}
}
the dropdown data are coming from nodejs and images from nodejs also. i want to get the user input as a JSON. i couldn't able to do that thats why i'm asking here kindly help me
please guide me on how to do that

Menu items are not clickable after rendering Google Maps container

My semantic-ui-react Menu component is acting strange when I add my google maps component to be rendered. Before I added my MapContainer, the FilterSection was working pretty fine. But after I render the MapContainer my sections in my Menu are no longer clickable nor do they react to my mouse hover. What should I do?
Snippet of render:
return (
<div>
<Navbar/>
<FilterSection/>
<ChatWidget/>
<div className="map-and-cards">
<MapContainer/> // This line causes the problem
<div style={containerStyle} className="cards-container">
<div class="card-columns" style={{gridTemplateColumns: '350px 350px', display: 'grid', rowGap: '50px', columnGap: '18px'}}>
<Cards listingData={listingData}/>
</div>
</div>
</div>
</div>
)
and my MapContainer.js:
import React from 'react';
import { Map, GoogleApiWrapper } from 'google-maps-react';
const style = {
position: 'relative',
top: '65px',
width: '47.5%', // 47.5
height: '85%',
};
const defaultCenter = {
lat: 41.04137, lng: 28.979530
}
export class MapContainer extends React.Component<MapProps> {
render() {
return (
<Map
style = {style}
google={this.props.google}
centerAroundCurrentLocation={true}
zoom={12}
initialCenter={defaultCenter}
/>
);
}
}
export default GoogleApiWrapper({
apiKey: (0)
})(MapContainer)
FilterSection.js:
import React, { Component } from "react";
import { Menu, Dropdown, Input, Button } from "semantic-ui-react";
import 'semantic-ui-css/semantic.min.css'
export class Price extends Component {
state = { isOpen: false };
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() {
const { activeItem } = this.state;
return (
<div style={{float: 'left'}}>
<Menu secondary >
<Menu.Item>
<Dropdown
text={"Price"}
className="item"
onClick={this.toggleOpen}
open={this.state.isOpen}
>
<Dropdown.Menu onClick={this.preventClosing}>
<Dropdown.Header icon="money" content={" Price Range"} />
<Dropdown.Divider />
<form
style = {{margin: '10px'}}
name="id"
type="number"
max={900}
action={<Button onClick={this.toggleOpen} content={"Send"} />}
>
<Input style={{zoom: '0.9'}} placeholder="min"/> — <Input style={{zoom: '0.9'}} placeholder="max"/>
</form>
</Dropdown.Menu>
</Dropdown>
</Menu.Item>
</Menu>
</div>
);
}
toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
preventClosing = e => e.stopPropagation();
}
export class BedsAndBaths extends Component {
state = { isOpen: false };
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() {
const { activeItem } = this.state;
return (
<div style={{float: 'left'}}>
<Menu secondary>
<Menu.Item>
<Dropdown
text={"Bedrooms & Livingrooms"}
className="item"
onClick={this.toggleOpen}
open={this.state.isOpen}
>
<Dropdown.Menu onClick={this.preventClosing}>
<form
style = {{margin: '10px'}}
name="id"
type="number"
max={900}
action={<Button onClick={this.toggleOpen} content={"Send"} />}
>
<Input style={{zoom: '0.9'}} placeholder="3"/> + <Input style={{zoom: '0.9'}} placeholder="1"/>
</form>
</Dropdown.Menu>
</Dropdown>
</Menu.Item>
</Menu>
</div>
);
}
toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
preventClosing = e => e.stopPropagation();
}
export class More extends Component {
state = { isOpen: false };
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() {
const { activeItem } = this.state;
return (
<div style={{float: 'left'}}>
<Menu secondary>
<Menu.Item>
<Dropdown
text={"More"}
className="item"
onClick={this.toggleOpen}
open={this.state.isOpen}
>
<Dropdown.Menu onClick={this.preventClosing}>
<Dropdown.Header icon="money" content={" Price Range"} />
<Dropdown.Divider />
<form
style = {{margin: '10px'}}
name="id"
type="number"
max={900}
action={<Button onClick={this.toggleOpen} content={"Send"} />}
>
<Input style={{zoom: '0.9'}} placeholder="min"/> — <Input style={{zoom: '0.9'}} placeholder="max"/>
</form>
</Dropdown.Menu>
</Dropdown>
</Menu.Item>
</Menu>
</div>
);
}
toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
preventClosing = e => e.stopPropagation();
}
export class Alert extends Component {
state = { isOpen: false };
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() {
const { activeItem } = this.state;
return (
<div style={{float: 'left', position: 'relative', top: '11.5px', left: '15px', zoom: '0.9'}}>
<Menu secondary >
<button class="ui button ">
Create Alert
</button>
</Menu>
</div>
);
}
toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
preventClosing = e => e.stopPropagation();
}
export class Search extends Component {
state = { isOpen: false };
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() {
const { activeItem } = this.state;
return (
<div style={{float: 'left', position: 'relative', top: '12px', right: '50px', zoom: '0.9'}}>
<Menu secondary >
<div style={{float: 'left', position: 'relative', right: '10px'}} class="ui input focus">
<input type="text" placeholder="Enter an adress, neigborhood, city, or ZIP code
" size="45"/>
</div>
<button class="ui button ">
Search
</button>
</Menu>
</div>
);
}
toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
preventClosing = e => e.stopPropagation();
}
export default function FilterSection(){
return (
<div style={{position: 'relative', left: '75px', bottom: '1px'}}><Search/><div style={{position: 'relative', right: '30px'}}><More/><BedsAndBaths/><Price/><Alert/></div></div>
)
}
As I said, only the MapContainer component is triggering the deactivation of the menu.
You can see the actual page at royaremlak.com/search

Maximum call stack size exceeded while integrating in react-id-swiper

I am Using rect-id-swiper for carousel in my project. below is my code.
class Slide extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
load: false,
next: "",
error: null
};
}
componentDidMount() {
this.setState({ loading: true });
const token = getTokenu();
Axios.get(ApiUrlConstant.getApiFullUrl("slide"), {
headers: {
Authorization: "Token " + token
}
})
.then(res => {
console.log(res.data.results);
this.setState({ data: res.data.results, loding: false });
})
.catch(error => {
this.setState({ error: error, loading: false });
});
}
renderCompetitionSlides = () => {
if (this.state.data.length === 0)
return (
<div
style={{
width: "100%",
display: "flex",
justifyContent: "center",
color: "#f3990f"
}}
>
<span>No Poster to display!</span>
</div>
);
return this.state.data.map(item => {
return (
<div key={item.id}>
<Link className="card" to="">
<div className="swiperimgweb">
<img style={{ width: "100%" }} src={item.poster} />
</div>
</Link>
</div>
);
});
};
render() {
const { data, error, load, next } = this.state;
SwiperCore.use([Autoplay, Navigation]);
const swiperhero = {
spaceBetween: 30,
centeredSlides: true,
autoplay: {
delay: 5000,
disableOnInteraction: false
},
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev"
}
};
return (
<div>
<Swiper {...swiperhero}>{this.renderCompetitionSlides()}</Swiper>
{this.state.load ? (
<div
id="slide-load"
style={{
marginTop: "100px",
marginBottom: "30px",
width: "100%",
display: "flex",
justifyContent: "center"
}}
>
<ClipLoader size={30} color={"#f3990f"} />
</div>
) : null}
</div>
);
}
}
export default Slide;
And I am trying to render these API's
I think I have done in right way. but still am getting error on console and The images are not coming as I need. click here to check the react-id-swiper.
scheduler.development.js:178 Uncaught RangeError: Maximum call stack size exceeded
What is the mean of above error and How can we fix this?

How to make div with selected color in colorpicker

For my app, I use react color picker https://casesandberg.github.io/react-color. I must make add button, and when the user clicks on this button it needs to show div(className is saved-color-placeholder) with the selected color. So, the background of div must be like a selected color. In function saveColor, I push the color in an empty array.
This is my code
class Colorpicker extends React.Component {
constructor(props) {
super(props);
this.state = {
displayColorPicker: false,
color: {
r: '0',
g: '0',
b: '0',
a: '1',
},
colorHex: "#000",
savedColors: []
};
}
handleClick = () => {
this.setState({ displayColorPicker: !this.state.displayColorPicker })
};
handleClose = () => {
this.setState({ displayColorPicker: false })
};
handleChange = (color) => {
this.setState({ color: color })
console.log(color)
};
saveColor = (color) => {
let savedColorsArray = this.state.savedColors;
savedColorsArray.push(this.state.color)
this.setState({
savedColors: savedColorsArray
})
console.log(this.state.savedColors)
}
render() {
const styles = reactCSS({
'default': {
color: {
width: '31px',
height: '31px',
borderRadius: '20px',
background: `rgba(${this.state.color.r}, ${this.state.color.g}, ${this.state.color.b}, ${this.state.color.a})`,
},
popover: {
position: 'absolute',
zIndex: '2',
},
savedColor: {
width: '28px',
height: '28px',
borderRadius: '14px',
marginRight: '8px',
background: `rgba(${this.state.color.r}, ${this.state.color.g}, ${this.state.color.b}, ${this.state.color.a})`
}
},
});
return (
<div className="text-color-container ">
<div className="selected-color-content">
<div className="hex-placeholder">
<p>{this.state.colorHex}</p>
</div>
<div className="switch" onClick={this.handleClick}>
<div style={styles.color} />
</div>
{
this.state.displayColorPicker ?
<div className="wrapper">
<div style={styles.popover}>
<div style={styles.cover} onClick={this.handleClose} />
<SketchPicker color={this.state.color} onChange={this.handleChange} />
<div className="saved-colors">
<span >Saved colors</span>
<div className="painted-colors">
<button onClick={this.saveColor} className="btn-save-color">Add</button>
<span slassName="saved-color-placeholder">
<div style={styles.savedColor}/>
</span>
</div>
</div>
</div>
</div>
:
null
}
</div>
</div>
)
}
}
export default Colorpicker
I am not sure this is the best solution but I think it can be good enough.
You can use arrays inside your style prop. So what you could do is:
<div style={[styles.savedColor,{backgorundColor: selectedColor}]>
Hope this will helps.

Resources