Dynamically render multiple buttons - javascript

I am new in react Js and i want to build a multiple buttons like on link.
Can anybody help me .It will be very helpful to understand statements and components .
http://noxious-ornament.surge.sh/
i try to write something like this but i don't know how to continue.
import React, { Component } from 'react'
import './Ar.css';
class Ar extends Component {
constructor() {
super();
this.state = {
buttonPressed: 0
// 0 could be your default view
}
}
handleClick = (button) => {
this.setState({ buttonPressed: button })
}
render() {
return(
<div>
<button
className='button1'
onClick={() => this.handleClick(1)}
> BUTTON 1
</button>
<button
className='button2'
onClick={() => this.handleClick(1)}
> BUTTON 2
</button>
<button
className='button2'
onClick={() => this.handleClick(1)}
> BUTTON 3
</button>
}
</div>
)
}
}
export default Ar

This is a start. Next I'd add react-router-dom so you can load the SomePage component.
const {Component} = React;
function SomePage(props){
return (
<div>
Button {props.value} has been pressed!
<button>back</button>
</div>
)
};
class App extends Component {
constructor() {
super();
this.state = {
buttonPressed: 0,
buttonCount: [1,2,3,4,5]
}
}
handleClick = (event) => {
this.setState({ buttonPressed: event.target.id });
}
render() {
return(
<div>
{this.state.buttonCount.length > 0 ? this.state.buttonCount.map((item,index) => (
<button id={item} key = {index} onClick={()=>this.handleClick} className={`button${item}`}>
{item}
</button>
))
: null
}
</div>
)
}
}
// Render
ReactDOM.render(
<App />,
document.getElementById("react")
);
.button1 {
background-color: green;
}
.button2 {
background-color: blue;
}
.button3 {
background-color: red;
}
.button4 {
background-color: yellow;
}
.button5 {
background-color: purple;
}
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

You can have a state variable in the type of array:
this.state = {
buttonPressed: 0,
burronArray:[
{
id : 1,
name : "Button 1"
},
{
id : 2,
name : "Button 2"
},
]
}
and in the render function:
render() {
return(
<div>
{this.state.buttonArray.length > 0 ? buttonArray.map((button, index) => return(
<button
key={index}
value = {button.id}
className='button1'
onClick={() => this.handleClick(1)}
> {button.name}
</button>
)) : null}
</div>
)
}

Related

focusing on the last input when adding an entry with a button

When the inputs are focused, I make the borders red with css.
But I can't autofocus on the most recently added input.
codesandbox: Example
import React from "react";
import "../src/styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { values: [] };
}
createUI() {
return this.state.values.map((el, i) => (
<div key={i} style={{ marginBottom: "1rem" }}>
<style>
{`
.test:focus-within{
border:3px solid red !important;
}
`}
</style>
<div className="test">
<input type="text" />
</div>
</div>
));
}
addClick() {
this.setState((prevState) => ({ values: [...prevState.values, ""] }));
}
render() {
return (
<>
{this.createUI()}
<input
type="button"
value="add more"
onClick={this.addClick.bind(this)}
/>
</>
);
}
}
export default App;
How can I autofocus the last added input and make its borders red?
can create a useRef and assign it to the latest input
class App extends React.Component {
constructor(props) {
super(props);
this.state = { values: [] };
this.lastRef = React.createRef();
}
createUI() {
return this.state.values.map((el, i) => (
.....
<input ref={i === this.state.values.length - 1 ? this.lastRef : undefined} type="text" />
....
));
}
addClick() {
this.setState((prevState) => ({ values: [...prevState.values, ""] }),
() => {
this.lastRef.current.focus()
});
}
Demo

How can I pass a function with a index element down the component?

When the modal appears, I want to delete the list item. From the App component, I want to pass the remove function to the 'modal' component. When modal appears -> I click delete -> the element in the list disappears? how to move the index of the removed item to the modal?
Click icon cross inside li --> display modal ---> click delete --> remove element
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Modal from "./components/Modal";
class App extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: false,
arrays: [],
index: null
};
}
remove = index =>
this.setState({
arrays: [
...this.state.arrays.slice(0, index),
...this.state.arrays.slice(index + 1)
],
isOpen: false
});
toggleModal = () => {
this.setState({
isOpen: !this.state.isOpen,
index: index
});
};
render() {
return (
<div className="App">
<ul>
{this.state.arrays.map((array, index) => (
<li key={index}>
{array.name}
<i className="fa fa-cross" onClick={() =>
this.toggleModal(index)}/>
</li>
))}
</ul>
<Modal
show={this.state.isOpen}
index={this.state.index}
onRemove={this.remove}
onClose={this.toggleModal}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
components/modal.js
import React, { Component } from "react";
class Modal extends Component {
render() {
// Render nothing if the "show" prop is false
if (!this.props.show) {
return null;
}
// The gray background
const backdropStyle = {
position: "fixed",
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: "rgba(0,0,0,0.3)",
padding: 50
};
// The modal "window"
const modalStyle = {
backgroundColor: "#fff",
borderRadius: 5,
maxWidth: 500,
minHeight: 300,
margin: "0 auto",
padding: 30
};
return (
<div className="backdrop" style={backdropStyle}>
<div className="modal" style={modalStyle}>
{this.props.children}
<div className="footer">
<button onClick=
{this.props.onRemove(this.props.index}>Delete</button>
<button onClick={this.props.onClose}>Cancel</button>
</div>
</div>
</div>
);
}
}
export default Modal;
Pass an index of each todo to toggleModal and pull the index of the todo from the remove function.
remove = () =>
this.setState({
arrays: [
...this.state.arrays.slice(0, this.state.index),
...this.state.arrays.slice(this.state.index + 1)
],
isOpen: false
});
toggleModal = (index) => {
this.setState({
isOpen: !this.state.isOpen,
index: index
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<div id="root"></div>
<script type="text/babel">
class Modal extends React.Component {
render() {
// Render nothing if the "show" prop is false
if (!this.props.show) {
return null;
}
// The gray background
const backdropStyle = {
position: "fixed",
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: "rgba(0,0,0,0.3)",
padding: 50
};
// The modal "window"
const modalStyle = {
backgroundColor: "#fff",
borderRadius: 5,
maxWidth: 500,
minHeight: 300,
margin: "0 auto",
padding: 30
};
return (
<div className="backdrop" style={backdropStyle}>
<div className="modal" style={modalStyle}>
{this.props.children}
<div className="footer">
<button onClick={() =>this.props.onRemove(this.props.index)}>Delete</button>
<button onClick={this.props.onClose}>Cancel</button>
</div>
</div>
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isOpen: false,
arrays: [{ name: 'Study'}, {name: 'Cook'}],
index: null
};
}
remove = () =>
this.setState({
arrays: [
...this.state.arrays.slice(0, this.state.index),
...this.state.arrays.slice(this.state.index + 1)
],
isOpen: false
});
toggleModal = (index) => {
this.setState({
isOpen: !this.state.isOpen,
index: index
});
};
render() {
return (
<div className="App">
<ul>
{this.state.arrays.map((todo, index) => (
<li key={index}>
{todo.name}
<i className="fa fa-times" onClick={() => this.toggleModal(index)}/>
</li>
))}
</ul>
<Modal
show={this.state.isOpen}
index={this.state.index}
onRemove={this.remove}
onClose={this.toggleModal}
/>
</div >
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>

Add prop when onClick in ReactJS

I would like to change current li item color when I click it.
How to add prop to item(using array map), when I click it? I use styled-components
const Li = styled.li`
color: ${props => (props.checked ? "red" : "green")};
`;
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: "",
items: []
};
}
render() {
const ShowItems = this.state.items.map((item, index) => {
return (
<Li key={index}>
{item}
<button onClick={() => this.deleteItemHandler(index)}> Delete</button>
</Li>
);
});
return (
<Wrapper>
<AddItem
addItemHandler={this.addItem}
InputValue={this.state.value}
InputValueHandler={this.inputValue}
/>
{ShowItems}
</Wrapper>
);
}
}
Check out this code working on CodeSandBox
import React, { Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import styled from "styled-components";
const Li = styled.li`
color: ${props => (props.checked ? "red" : "green")};
`;
class App extends Component {
state = {
value: "",
items: [],
selected: -1
};
handleChange = e => {
this.setState({
[e.currentTarget.name]: e.currentTarget.value
});
};
handleAdd = () => {
const { items, value } = this.state;
this.setState({
items: [...items, value],
value: ""
});
};
handleRemove = index => {
const { items, selected } = this.state;
items.splice(index, 1);
if (index < selected) index = selected - 1;
if (index === selected) index = -1;
if (index > selected) index = selected;
this.setState({
items: items,
selected: index
});
};
handleActiveItem = index => {
this.setState({ selected: index });
};
render() {
const { value, items, selected } = this.state;
return (
<div>
<input
type="text"
value={value}
name="value"
onChange={this.handleChange}
/>
<button
style={{ margin: "0px 5px" }}
disabled={!value}
className="btn btn-sm btn-success"
onClick={this.handleAdd}
>
+
</button>
<ul className="li">
{items.map((item, index) => (
<Li key={index} checked={selected === index}>
<span onClick={() => this.handleActiveItem(index)}>{item}</span>
<button
style={{ margin: "1px 5px" }}
className="btn btn-sm btn-danger"
onClick={() => this.handleRemove(index)}
>
X
</button>
</Li>
))}
</ul>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Ignore the handlers if you don't need them. Thanks to this effort I learnt about styled-components and discovered CodeSandBox.
EDIT :
Added a <span> inside <li> to avoid nested onClick, previously <li> (parent) and <button> (child) both had onClick attribute. On button Click two onClick events were fired resulting in unexpected behaviour in some use cases. You must correct this in your code.
Added logic to keep item selected when an item before it is deleted.
Added button validation to avoid adding empty string/items in list.
Also updated CodeSandBox Code to reflect above changes.
So you need keep track of the active index, and use it too change the color of the active component color.
state ={
activeIndex: void 0
}
const Li = styled.li`
color: ${props => props.checked ? "red" : "green"};
;`
deleteItemHandler = (index) => {
this.setState({
activeIndex: index
})
}
render() {
const ShowItems = this.state.items.map((item, index) => {
return (
<Li key={index} checked={index === this.state.activeIndex} > {item} < button onClick={() => this.deleteItemHandler(index)
}> Delete</button ></Li >
)
})
return (
<Wrapper>
<AddItem
addItemHandler={this.addItem}
InputValue={this.state.value}
InputValueHandler={this.inputValue}
/>
{ShowItems}
</Wrapper>
);
Try this
const Li = styled.li`
color: ${props => props.checked ? "red" : "green"};
;`
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: "",
items: [],
currentChecked: null
};
}
render() {
const ShowItems = this.state.items.map((item, index) => {
return (
<Li key={index} checked={index === this.state.currentChecked} >
{item}
<button onClick={() => this.setState({currentChecked: index})}>Delete</button >
</Li >
)
})
return (
<Wrapper>
<AddItem
addItemHandler={this.addItem}
InputValue={this.state.value}
InputValueHandler={this.inputValue}
/>
{ShowItems}
</Wrapper>
);

Toggle only content from clicked button in React.js

I'm trying to change display of div.Filters on click of plus or minus button. The button changes on click, if it's a + changes to -, and vice versa.
Here's the code:
export class NavLeftMobile extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
isToggle: true
};
}
handleClick(e) {
this.setState({
isToggle: !this.state.isToggle
});
}
render() {
let button;
if (this.state.isToggle) {
button = (
<button className="Menos" onClick={() => this.handleClick()}>
-
</button>
);
} else {
button = (
<button className="Menos" onClick={() => this.handleClick()}>
+
</button>
);
}
return (
<div>
<div className="NavLeftMobile">
<h1>categories</h1>
<h3>Manufacturer{button}</h3>
<div
className="Filters"
style={{ display: this.state.isToggle ? "block" : "none" }}
>
<p>Lusograph (10)</p>
</div>
<h3>Color{button}</h3>
<div
className="Filters"
style={{ display: this.state.isToggle ? "block" : "none" }}
>
<p>Black (10)</p>
</div>
</div>
</div>
);
}
}
So, when clicking on one of the buttons, handleClick function is called and the display from div.Filters changes, if it's block to none and vice versa.
Basically, I want to toggle each section independent from each other.
If you want each section to be Collapsible and indepent, then the state should not live on your wrapper component, instead you can create another class component that keeps track of it.
class Collapsible extends React.Component {
constructor(props) {
super(props);
this.state = {
collapsed: true
};
}
onToggle = () => {
const { collapsed } = this.state;
this.setState(() => ({
collapsed : !collapsed
}))
}
render () {
const { title, children } = this.props;
const { collapsed } = this.state;
return (
<div>
<h3>
{title}
<a onClick={this.onToggle}>
{collapsed ? '+' : '-'}
</a>
</h3>
<div style={{
display : collapsed ? "block" : "none"
}}>
{children}
</div>
</div>
);
}
}
class NavLeftMobile extends React.Component {
render() {
return (
<div>
<div className="NavLeftMobile">
<h1>categories</h1>
<Collapsible title="Manufacturer">
Lusograph (10)
</Collapsible>
<Collapsible title="Color">
Black (10)
</Collapsible>
</div>
</div>
);
}
}
ReactDOM.render(
<NavLeftMobile/>,
document.querySelector('#app')
);

How add onMouseOver,onMouseEnter in reactjs?

Here, i am using onMouseOver event in react but it not works fine for me.
I use proper way how to use, call and set State.
Here is my code anyone please help.
import React from 'react';
const style = {
color:"black",
fontSize:16,
borderRadius:4,
border: "1px solid grey",
lineHeight: "28px",
background: "white",
padding: 3,
margin:3,
}
const highlightStyle = {
color:"black",
fontSize:16,
border: "1px solid grey",
background:"lightblue",
borderRadius:4,
lineHeight: "25px",
padding: 3,
margin:5
}
export default class SplitSpansPreview extends React.Component {
constructor(props){
super(props)
this.state = {
color_black: true,
hover: false
}
this.changeColor = this.changeColor.bind(this)
this.onHover = this.onHover.bind(this)
this.hoverOn = this.hoverOn.bind(this)
this.hoverOff = this.hoverOff.bind(this)
}
onHover() { alert("hello")
this.setState({ hover: true });
}
hoverOn(){alert("hcek")
// this.setState({ hover: true });
}
hoverOff(){ alert("kol")
// this.setState({ hover: false });
}
changeColor() {
const id = this.props.atId;
const self = this
this.setState({color_black: !this.state.color_black}, () => {
if(this.state.color_black){
self.props.getDisselectedId(id);
} else {
self.props.getSelectedId(id);
}
});
}
createMarkup(data) {
return {__html: data}
}
render(){
let checkBreak = this.props.item.substring(0,4)
if(checkBreak == '<br>' || checkBreak == ' <br') {
const itemLength = this.props.item.length
if(checkBreak == '<br>') {
var item = this.props.item.substring(4,itemLength)
} else {
var item = this.props.item.substring(5,itemLength)
}
if(this.props.punctuation) {
return(
<span>
<br/>
<span id={this.props.atId}
className = {this.props.classword}
style={this.state.color_black ? style: highlightStyle}
onClick={this.changeColor}
onMouseOver={this.onHover}
>
{item}
</span>
<span className = {this.props.classword}>
{this.props.punctuation}
</span>
</span>
)
} else {
return(
<span>
<br/>
<span id={this.props.atId}
className = {this.props.classword}
style={this.state.color_black ? style: highlightStyle}
onClick={() => this.changeColor()}
onMouseEnter={() => this.hoverOn()}
onMouseLeave={() => this.hoverOff()}
>
{item}
</span>
</span>
)
}
} else {
if(this.props.punctuation) {
return(
<span>
<span id={this.props.atId}
className = {this.props.classword}
style={this.state.color_black ? style: highlightStyle}
onClick={this.changeColor}
>
{this.props.item}
</span>
<span className = {this.props.classword}>
{this.props.punctuation}
</span>
</span>
)
} else {
return(
<span id={this.props.atId}
className = {this.props.classword}
style={this.state.color_black ? style: highlightStyle}
onClick={this.changeColor}
>
{this.props.item}
</span>
)
}
}
}
}
Finally i edit my code and here is my whole code please find error and let me know.otherwise if you change in my code i am happy if it work.
i read lots of article but can't work so please see what happen.
You will have to pass the function in different way, so that thisvariable correctly points to the component and this.setState works.
One of the way is givenbelow
<span id={this.props.atId}
className = {this.props.classword}
style={this.state.color_black ? style: highlightStyle}
onClick={() => this.changeColor()}
onMouseEnter={() => this.hoverOn()}
onMouseLeave={() => this.hoverOff()}
>
{item}
</span>
I checked the code with following working example
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
class App extends Component {
constructor() {
super();
this.state = {
name: 'React',
message: ""
};
}
onMouseEnter() {
this.setState({message: 'Mouse Enter'})
}
onMouseLeave() {
this.setState({message: 'Mouse Leave'})
}
render() {
return (
<div>
<Hello name={this.state.name} />
<p onMouseEnter={() => this.onMouseEnter()} onMouseLeave={() => this.onMouseLeave()}>
Hover here!
</p>
<span>{this.state.message}</span>
</div>
);
}
}
render(<App />, document.getElementById('root'));

Categories

Resources