Map function in Reactjs is putting addition objects in the array - javascript

I am trying to have a set of input fields right after one another like a terminal.
The Page component looks like this
import React, { Component } from "react";
import NewLine from "./newLine";
export class Page extends Component {
state = {
numberOfLine: 0,
lines: [{ value: "", id: 0, displayInputs: true}]
};
render() {
return (
<div className="container">
<div className="terminal">
<p className="prompt">
Hey there! This is a pre rendered line.
</p>
{this.state.lines.map(l => (
<NewLine
key={this.state.numberOfLine}
handelWhatever={this.handelWhatever}
line={l}
></NewLine>
))}
</div>
</div>
);
}
handelWhatever = (string_value, Tid) => {
// console.log(string_value, Tid);
// console.log(this.state.lines.filter(l => l.id != Tid));
const num = this.state.numberOfLine + 1;
this.setState({
numberOfLine: this.state.lines.length + 1,
lines: [
...this.state.lines.filter(line => line.id !== Tid),
{ value: string_value, id: Tid, displayInput: false },
{ value: "", id: num, displayInput: true }
]
});
};
export default Page;
and my NewLine component looks like this
import React, { Component } from "react";
export class NewLine extends Component {
state = {
id: this.props.line.id,
value: this.props.line.value,
displayInput: this.props.line.displayInput
};
render() {
return (
<React.Fragment>
<p className=output>
{this.state.displayInput && (
<input
type="text"
className="here"
value={this.state.value}
onChange={this.handleChange}
onKeyDown={this.handelEnter}
/>
)}
{this.state.value}
</p>
</React.Fragment>
);
}
handleChange = event => {
this.setState({ value: event.target.value });
};
handelEnter = event => {
if (event.key === "Enter") {
this.props.handelWhatever(event.target.value, this.state.id);
}
};
}
export default NewLine;
When I enter the "something" in the input it should make a NewLine component and delete the input from the previous one so that user can type on the newly rendered line that is why I have bool in the New Line state.
The states updates perfectly but when i user input it takes all the previous ones and render them, i.e,
Initial Stage
> Hey there! This is a pre rendered line.
>
User Input : 'ls'
> Hey there! This is a pre rendered line.
> ls
>
User Input : 'cd'
> Hey there! This is a pre rendered line.
> ls
> ls
> cd
and so on
I don't know what is going on I tried printing the state of the Parent component and it has desired number of lines In the map if I do console.log just after one input I will get
{value: "ls", id: 1, displayInput: false}
{value: "ls", id: 1, displayInput: false}
{value: "", id: 2, displayInput: true}
console logging in map is like this
{this.state.lines.map(l => {
console.log(l);
return (
<NewLine
key={this.state.numberOfLine}
handelWhatever={this.handelWhatever}
line={l}
></NewLine>
);
})}

You need to use the id of the line for the key for each NewLine component.
Also, you need to use {this.props.line.value} instead of {this.state.value} in the NewLine component.
See below
<React.Fragment>
<p className=output>
{this.state.displayInput && (
<input
type="text"
className="here"
value={this.state.value}
onChange={this.handleChange}
onKeyDown={this.handelEnter}
/>
)}
{this.props.line.value} OR {this.state.value}
</p>
</React.Fragment>
See this codepen.
In the code pen I use a div instead of React.Fragment but that's just because the fragment was throwing an error in a codepen.
EDIT
It actually works with this.state.value so depending on use case, both this.props.line.value and this.state.value works.

Related

Why is FieldSelect returning a string while FieldCheckbox returning an object?

FieldSelect component from Sharetribe docs is returning me a string while FieldCheckbox is returning a JSON object.
I want FieldSelect to save a JSON object in a particular case.
How do I do this?
Following is my code for reference,
I am new to REACT and would be really thankful to anyone explaining why this is happening.
Code Calling
<FieldSelect
name={subGroupCategoryKey}
id={subGroupCategoryKey}
label={categoryLabel}
>
{relevantSubGroupCategoryOptions.map(c => (
<option key={c.key} value={c.key}>
{c.label}
</option>
))}
</FieldSelect>
FieldSelect
import React from 'react';
import PropTypes from 'prop-types';
import { Field } from 'react-final-form';
import classNames from 'classnames';
import { ValidationError } from '../../components';
import css from './FieldSelect.module.css';
const FieldSelectComponent = props => {
const { rootClassName, className, id, label, input, meta, children, ...rest } = props;
if (label && !id) {
throw new Error('id required when a label is given');
}
const { valid, invalid, touched, error } = meta;
// Error message and input error styles are only shown if the
// field has been touched and the validation has failed.
const hasError = touched && invalid && error;
const selectClasses = classNames(css.select, {
[css.selectSuccess]: valid,
[css.selectError]: hasError,
});
const selectProps = { className: selectClasses, id, ...input, ...rest };
const classes = classNames(rootClassName || css.root, className);
return (
<div className={classes}>
{label ? <label htmlFor={id}>{label}</label> : null}
<select {...selectProps}>{children}</select>
<ValidationError fieldMeta={meta} />
</div>
);
};
FieldSelectComponent.defaultProps = {
rootClassName: null,
className: null,
id: null,
label: null,
children: null,
};
const { string, object, node } = PropTypes;
FieldSelectComponent.propTypes = {
rootClassName: string,
className: string,
// Label is optional, but if it is given, an id is also required so
// the label can reference the input in the `for` attribute
id: string,
label: string,
// Generated by final-form's Field component
input: object.isRequired,
meta: object.isRequired,
children: node,
};
const FieldSelect = props => {
return <Field component={FieldSelectComponent} {...props} />;
};
export default FieldSelect;
FieldCheckbox
import React from 'react';
import { node, string } from 'prop-types';
import classNames from 'classnames';
import { Field } from 'react-final-form';
import css from './FieldCheckbox.module.css';
const IconCheckbox = props => {
const { className, checkedClassName, boxClassName } = props;
return (
<SVG >
</svg>
);
};
IconCheckbox.defaultProps = { className: null, checkedClassName: null, boxClassName: null };
IconCheckbox.propTypes = { className: string, checkedClassName: string, boxClassName: string };
const FieldCheckboxComponent = props => {
const {
rootClassName,
className,
svgClassName,
textClassName,
id,
label,
useSuccessColor,
onChange: handleChange,
...rest
} = props;
const classes = classNames(rootClassName || css.root, className);
// This is a workaround for a bug in Firefox & React Final Form.
// https://github.com/final-form/react-final-form/issues/134
const handleOnChange = (input, event) => {
const { onBlur, onChange } = input;
onChange(event);
onBlur(event);
handleChange && handleChange(event);
};
const successColorVariantMaybe = useSuccessColor
? {
checkedClassName: css.checkedSuccess,
boxClassName: css.boxSuccess,
}
: {};
return (
<span className={classes}>
<Field type="checkbox" {...rest}>
{props => {
const input = props.input;
return (
<input
id={id}
className={css.input}
{...input}
onChange={event => handleOnChange(input, event)}
/>
);
}}
</Field>
<label htmlFor={id} className={css.label}>
<span className={css.checkboxWrapper}>
<IconCheckbox className={svgClassName} {...successColorVariantMaybe} />
</span>
<span className={classNames(css.text, textClassName || css.textRoot)}>{label}</span>
</label>
</span>
);
};
FieldCheckboxComponent.defaultProps = {
className: null,
rootClassName: null,
svgClassName: null,
textClassName: null,
label: null,
};
FieldCheckboxComponent.propTypes = {
className: string,
rootClassName: string,
svgClassName: string,
textClassName: string,
// Id is needed to connect the label with input.
id: string.isRequired,
label: node,
// Name groups several checkboxes to an array of selected values
name: string.isRequired,
// Checkbox needs a value that is passed forward when user checks the checkbox
value: string.isRequired,
};
export default FieldCheckboxComponent;
When a form is submitted the name of the input is key and the value is the value of user's input.
FieldSelect is a Final Form wrapper for HTML <select name="someName"> element. That element can only have a single value selected at the time, so the submit will contain something like someName: 'valueOfSelectedOption'.
FieldCheckbox is a wrapper for HTML <checkbox> element. Final Form library uses pretty widely used "array" setup for checkboxes that have the same name.
I mean, if your form has something like <checkbox name="asdf" value="a"/><checkbox name="asdf" value="b"/>, and user checks both of those checkboxes, the submitted value would look like this: asdf: ["a", "b"].
Note: Without Final Form library, the default HTML submit output would have been asdf=a&asdf=b.
So, FieldCheckbox is actually using array as an output format instead of JSON (although, they look the same in this case).
Here are a couple of links to React Final Form that you might want to check:
https://final-form.org/docs/react-final-form/
http://jinno.io/app/12/?source=react-final-form
If you want to change the field's value to something else than what it becomes by default, you should check parse (and format) field props:
https://final-form.org/docs/react-final-form/types/FieldProps#parse
https://final-form.org/docs/react-final-form/types/FieldProps#format

React changing the states of the whole elements in the map function, not only the button that is pressed

Hello everyone, I am trying to passing a method through a context api component to another component which, i have a map function there. I want my showInfo state changes to true or false depending on the button clicking, when i clicked the button, all the showInfo's of my states is changes, so thats not what i want, I want that specific item to change when i press to it. Can someone explaine where is the mistake that i've made?
MY CONTEXT APİ
import React from "react";
export const ToursContext = React.createContext();
class ToursContextProvider extends React.Component {
constructor(props) {
super(props);
this.changeState = this.changeState.bind(this);
this.state = {
tours: [
{
id: 0,
imageURL:
"https://images.unsplash.com/photo-1524231757912-21f4fe3a7200?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1351&q=80",
title: "İstanbul'un Güzelliğinin Sadece Bir Parçası Galata Kulesi",
showInfo: true,
info: "LOREM İPSUM AMET 1",
},
{
id: 1,
imageURL:
"https://images.unsplash.com/photo-1541432901042-2d8bd64b4a9b?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1319&q=80",
title: "Tarihi Süleymaniye Camii",
showInfo: true,
info: "LOREM İPSUM AMET 2",
},
],
};
}
changeState(itemdelete) {
this.setState({
showInfo: !this.state.showInfo,
});
console.log(itemdelete);
}
render() {
return (
<ToursContext.Provider
value={{ ...this.state, changeState: this.changeState }}
>
{this.props.children}
</ToursContext.Provider>
);
}
}
export default ToursContextProvider;
MY MAP LIST COMPONENT
import React from "react";
import { ToursContext } from "../contexts/Tours";
function Tours() {
return (
<div className="container">
<div className="row">
<ToursContext.Consumer>
{(value) => {
const { changeState } = value;
return value.tours.map((item) => (
<div className="col-md-4" key={item.id}>
<div className="card bg-dark text-white">
<img src={item.imageURL} className="card-img" alt="..." />
<div className="card-img-overlay">
<h5 className="card-title">{item.title}</h5>
<button
type="button"
onClick={changeState.bind(this, item)}
className="btn-sm btn-primary"
>
Bilgiyi Göster!
</button>
</div>
{value.showInfo ? "true" : "false"}
</div>
</div>
));
}}
</ToursContext.Consumer>
</div>
</div>
);
}
export default Tours;
You state is atomic. This means that it is treated as a single value. With classes, you have option to modify state object partially. For example, you have object with fields a and b. You can change both fields at once, only a or only b. But there is no option to modify state deeply. Let's imagine that you have state object like this:
{
"a": { "subfield_1": [], "subfield_2": "some string"},
"b": 3
}
You again, can modify a or b, but if you want to add item into array a.subfield_1 or change a.subfield_2, you will have to modify whole a, like this:
setState({
a: {
...a,
subfield_1: this.state.a.subfield_1.concat("new item"),
},
});
In you case, to change something inside tours key, you will have to modify whole tours key. It would be something like this:
changeState(itemdelete) {
this.setState({
tours: tours.map((item) =>
item.id !== itemdelete.id ? item : { ...item, showInfo: !item.showInfo }
),
});
}

React: Handling mapped states

I'm very new to coding and trying to figure out an issue I have come across.
I am using axios to pull a json file and store it in a state. (I am also using Redux to populate the form)
Then I am using .map() to dissect the array and show one value from within each object in the array.
example json:
unit :
[
{
designName : x,
quantity : 0,
},
{
designName : y,
quantity : 0,
},
{
designName : z,
quantity : 0,
}
]
I have then added an input to select the quantity of the value mapped and now I want to give that value back to the state, in order to send the entire modified json back to the API with Axios.
I feel like I'm close but I'm unsure what I need to do with the handleQuantity function.
Here's my code:
import React, { Component } from 'react';
import store from '../../redux_store'
import axios from 'axios';
import { Button, Card } from 'react-bootstrap'
import { Link } from 'react-router-dom'
store.subscribe(() => {
})
class developmentSummary extends Component {
constructor(props) {
super(props)
this.state = {
prjName: store.getState()[0].developmentName,
units: []
}
}
componentDidMount() {
axios.get('https://API')
.then(
res => {
console.log(res)
this.setState({
units: res.data.buildings
})
console.log(this.state.units.map(i => (
i.designName
)))
}
)
}
handleQuantity() {
}
render() {
return (
<>
<div className="Text2">
{this.state.prjName}
</div>
<div className="Text2small">
Please select the quantity of buildings from the list below
</div>
<ul>
{this.state.units.map((object, i) => (
<div className="Card-center">
<Card key={i} style={{ width: "50%", justifyContent: "center" }}>
<Card.Body>{object.designName}</Card.Body>
<Card.Footer>
<input
className="Number-picker"
type="number"
placeholder="0"
onChange={this.handleQuantity}
/>
</Card.Footer>
</Card>
</div>
))}
</ul>
Thanks in advance!
You have to pass the change event, unit object and the index to handleQuantity and then paste your changed unit as new object in between unchanged units.
Here is the code:
<input
className="Number-picker"
type="number"
placeholder="0"
onChange={(event) => this.handleQuantity(event, object, i)}
/>;
And the code for handleQuantity
handleQuantity = (event, unit, index) => {
const inputedNumber = +event.target.value; // get your value from the event (+ converts string to number)
const changedUnit = { ...unit, quantity: inputedNumber }; // create your changed unit
// place your changedUnit right in between other unchanged elements
this.setState((prevState) => ({
units: [
...prevState.units.slice(0, index),
changedUnit,
...prevState.units.slice(index + 1),
],
}));
}

Color Input in React: The format is "#rrggbb" where rr, gg, bb are two-digit hexadecimal numbers

Full Warning:
react-dom.development.js:2592 The specified value "" does not conform to the required format. The format is "#rrggbb" where rr, gg, bb are two-digit hexadecimal numbers.
The code IS WORKING FINE. It is doing what it is supposed to do, which is: each input changes the background color of the squares that appear/get updated once the button is pressed.
The only instance when the code was working and the warning was not appearing- was during development as i was messing with the color input and I was trying to change the background of a mockdiv that was part of the same component as the input. The second i lifted state it started behaving like this.
But the BEST PART IS: When I tell It to Console.log the this.state.color.hex (which is the value that changes the background color) It console.logs "#00ff40" "#ff0000" "#0000ff" AND "#ffff00" - Which is why I have no idea how to get rid of this warning.
I don't think this error is caused by the changeHandler function. I have had MANY different versions of this function and it has had little impact on this warning. As well, the other question to this warning (Warning when using color control in React JS ) has another completely different version of a changeHandler function and still has the same error. AND I originally had a one single changeHandler function for all instances of the value color prop, and the error was still there. BUT if it is- I would love to know how to change it if it means getting rid of this warning.
The structure summary is:
Checkbox => ButtonPerSquare =>HOME
Squares => SquaresWrapper =>HOME
Then Home merges the two and renders the squares on the click of the button, which is also on Home.
Checkbox.js: //i know is not a befitting name, but it was already called like that on my template for each new project.
import React from "react";
class CheckBoxes extends React.Component {
render() {
return (
<div>
<input
type={this.props.type}
className={this.props.class}
value={
this.props.class === "input1"
? this.props.color1
: this.props.class === "input2"
? this.props.color2
: this.props.class === "input3"
? this.props.color3
: this.props.class === "input4"
? this.props.color4
: console.log("blue")
}
onChange={
this.props.class === "input1"
? event => this.props.handleChange1(event)
: this.props.class === "input2"
? event => this.props.handleChange2(event)
: this.props.class === "input3"
? event => this.props.handleChange3(event)
: this.props.class === "input4"
? event => this.props.handleChange4(event)
: console.log("blue")
}
/>
<span>{this.props.sp1}</span>
</div>
);
}
}
export default CheckBoxes;
ButtonPerSquare.js:
import React, { Component } from "react";
import Checkboxes from "./Checkboxes";
// import "./../App.css";
const numbers = ["1", "2", "3", "4"];
// const colors = ["#ffffff", "#F7E3B3", "#71EB92", "#000fff"];
const classes = ["input1", "input2", "input3", "input4"];
class HeaderButtons extends Component {
render() {
//sp is for the span element in the Checkboxes function.
return (
<header className={this.props.headerClass}>
{numbers.map((nums, col) => {
// const keys = numbers[nums];
// console.log(keys);
return (
<Checkboxes
color1={this.props.color1}
color2={this.props.color2}
color3={this.props.color3}
color4={this.props.color4}
// color2={this.props.color2}
// color3={this.props.color3}
// color4={this.props.color4}
handleChange1={event => this.props.handleChange1(event)}
handleChange2={event => this.props.handleChange2(event)}
handleChange3={event => this.props.handleChange3(event)}
handleChange4={event => this.props.handleChange4(event)}
//this.props.handleChange}
background={this.props.background}
// className="ColorInput"
// color={this.props.color}
sp1={nums}
key={nums}
type="color"
// defaultValue={colors[col]}
class={classes[col]}
// value="red"
/>
);
})}
{/* one parethesis for return.. one curly for the funct... another parenthesis for map... and the blue curly THEN closing header */}
</header>
);
}
}
export default HeaderButtons;
Square.js
import React, { Component } from "react";
class Squares extends Component {
render() {
return (
<div
id={this.props.id}
className="Square"
style={{
background:
this.props.id === "square1"
? this.props.background1
: this.props.id === "square2"
? this.props.background2
: this.props.id === "square3"
? this.props.background3
: this.props.id === "square4"
? this.props.background4
: console.log("blue")
}}
>
Blue
</div>
);
}
}
export default Squares;
SquaresWrapper.js:
import React, { Component } from "react";
import Squares from "./Squares";
// import "./../App.css";
const numbers = ["1", "2", "3", "4"];
// const backgrounds = ["#ffffff", "#F7E3B3", "#71EB92", "#000fff"];
const classes = ["square1", "square2", "square3", "square4"];
class SquaresWrapper extends Component {
// constructor(props) {
// super(props);
// this.state = {};
// }
render() {
//sp is for the span element in the Checkboxes function.
return (
<section className={this.props.sectionClass}>
{numbers.map((nums, col) => {
// const keys = numbers[nums];
// console.log(keys);
return (
<Squares
id={classes[col]}
key={nums}
background1={this.props.background1}
background2={this.props.background2}
background3={this.props.background3}
background4={this.props.background4}
// value="red"
/>
);
})}
{/* one parethesis for return.. one curly for the funct... another parenthesis for map... and the blue curly THEN closing header */}
</section>
);
}
}
export default SquaresWrapper;
Home:
import React, { Component } from "react";
import HeaderButtons from "./ButtonPerSquare";
import ReactDOM from "react-dom";
// import Paragraph from "./Paragraph";
import SquaresWrapper from "./squaresWrapper";
class Home extends Component {
constructor(props) {
super(props);
this.state = {
color1: { hex: "" },
color2: { hex: "" },
color3: { hex: "" },
color4: { hex: "" }
};
}
render() {
return (
<div className="creatorDiv">
<HeaderButtons
color1={this.state.color1.hex}
color2={this.state.color2.hex}
color3={this.state.color3.hex}
color4={this.state.color4.hex}
handleChange1={event =>
this.setState({
color1: { hex: event.target.value }
})
}
handleChange2={event =>
this.setState({
color2: { hex: event.target.value }
})
}
handleChange3={event =>
this.setState({
color3: { hex: event.target.value }
})
}
handleChange4={event =>
this.setState({
color4: { hex: event.target.value }
})
}
headerClass="HeaderDiv"
/>
<button
onMouseDown={() =>
ReactDOM.render(
<SquaresWrapper
sectionClass="squaresWrapper"
background1={this.state.color1.hex}
// {this.state.color1}
background2={this.state.color2.hex}
// {this.state.color2}
background3={this.state.color3.hex}
// {this.state.color3}
background4={this.state.color4.hex}
// {this.state.color4}
/>,
document.getElementById("blue")
)
}
>
Create Color
</button>
<div id="blue"></div>
</div>
);
}
}
export default Home;
a simple solution for this warning "This warning does not conform to the required format. The format is "#rrggbb" where rr, gg, bb are two-digit hexadecimal numbers."
use default value in input[type=color]
<input type="color" name="xyz" value="#ffffff" id="xyz" >
#ffffff is default value or format.
Not an exact answer, but the warning is coming from Blink which is Chrome's DOM implementation.
https://chromium.googlesource.com/chromium/src/+/011c27ced479c76cffd5093ce107082e4da657f3/third_party/blink/renderer/core/html/forms/color_input_type.cc#190
If you create an <input type=color> and then set the .value to an unsupported value, it will issue that warning. There's no way to disable this warning, you can only avoid it by not setting the .value to an invalid value.
MDN explains this a bit too:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/color#Value
Setting the value to anything that isn't a valid, fully-opaque, RGB color in hexadecimal notation will result in the value being set to #000000.
I can't speak for React, but maybe it does this sort of thing incidentally.
HTH.

Not rendering JSX from function in React

The function is getting the value of a button click as props. Data is mapped through to compare that button value to a key in the Data JSON called 'classes'. I am getting all the data correctly. All my console.logs are returning correct values. But for some reason, I cannot render anything.
I've tried to add two return statements. It is not even rendering the p tag with the word 'TEST'. Am I missing something? I have included a Code Sandbox: https://codesandbox.io/s/react-example-8xxih
When I click on the Math button, for example, I want to show the two teachers who teach Math as two bubbles below the buttons.
All the data is loading. Just having an issue with rendering it.
function ShowBubbles(props){
console.log('VALUE', props.target.value)
return (
<div id='bubbles-container'>
<p>TEST</p>
{Data.map((item,index) =>{
if(props.target.value == (Data[index].classes)){
return (
<Bubble key={index} nodeName={Data[index].name}>{Data[index].name}
</Bubble>
)
}
})}
</div>
)
}
Sandbox Link: https://codesandbox.io/embed/react-example-m1880
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
const circleStyle = {
width: 100,
height: 100,
borderRadius: 50,
fontSize: 30,
color: "blue"
};
const Data = [
{
classes: ["Math"],
name: "Mr.Rockow",
id: "135"
},
{
classes: ["English"],
name: "Mrs.Nicastro",
id: "358"
},
{
classes: ["Chemistry"],
name: "Mr.Bloomberg",
id: "405"
},
{
classes: ["Math"],
name: "Mr.Jennings",
id: "293"
}
];
const Bubble = item => {
let {name} = item.children.singleItem;
return (
<div style={circleStyle} onClick={()=>{console.log(name)}}>
<p>{item.children.singleItem.name}</p>
</div>
);
};
function ShowBubbles(props) {
var final = [];
Data.map((item, index) => {
if (props.target.value == Data[index].classes) {
final.push(Data[index])
}
})
return final;
}
function DisplayBubbles(singleItem) {
return <Bubble>{singleItem}</Bubble>
}
class Sidebar extends Component {
constructor(props) {
super(props);
this.state = {
json: [],
classesArray: [],
displayBubble: true
};
this.showNode = this.showNode.bind(this);
}
componentDidMount() {
const newArray = [];
Data.map((item, index) => {
let classPlaceholder = Data[index].classes.toString();
if (newArray.indexOf(classPlaceholder) == -1) {
newArray.push(classPlaceholder);
}
// console.log('newArray', newArray)
});
this.setState({
json: Data,
classesArray: newArray
});
}
showNode(props) {
this.setState({
displayBubble: true
});
if (this.state.displayBubble === true) {
var output = ShowBubbles(props);
this.setState({output})
}
}
render() {
return (
<div>
{/* {this.state.displayBubble ? <ShowBubbles/> : ''} */}
<div id="sidebar-container">
<h1 className="sidebar-title">Classes At School</h1>
<h3>Classes To Search</h3>
{this.state.classesArray.map((item, index) => {
return (
<button
onClick={this.showNode}
className="btn-sidebar"
key={index}
value={this.state.classesArray[index]}
>
{this.state.classesArray[index]}
</button>
);
})}
</div>
{this.state.output && this.state.output.map(item=><DisplayBubbles singleItem={item}/>)}
</div>
);
}
}
ReactDOM.render(<Sidebar />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
The issue here is ShowBubbles is not being rendered into the DOM, instead (according the sandbox), ShowBubbles (a React component) is being directly called in onClick button handlers. While you can technically do this, calling a component from a function will result in JSX, essentially, and you would need to manually insert this into the DOM.
Taking this approach is not very React-y, and there is usually a simpler way to approach this. One such approach would be to call the ShowBubbles directly from another React component, e.g. after your buttons using something like:
<ShowBubbles property1={prop1Value} <etc...> />
There are some other issues with the code (at least from the sandbox) that you will need to work out, but this will at least help get you moving in the right direction.

Categories

Resources