React JS Object - javascript

In below code i have not declared showPerson property in person object. But am getting result. Button has hide and show content when you click on button. Its working fine for me. But still i have doubt how come without declaring the property in object. Please explain it in simplest way.
import React, { Component } from "react";
import "./App.css";
import Person from "./Person/Person";
class App extends Component {
state = {
person: [
{ name: "Andrew", age: 32 },
{ name: "Stephen", age: 42 },
{ name: "Samuel", age: 62 }
]
};
changeTxt = () => {
const doesShow = this.state.showPerson;
this.setState({ showPerson: !doesShow });
};
render() {
let person = null;
if (this.state.showPerson) {
person = (
<div>
<Person
name={this.state.person[0].name}
age={this.state.person[0].age}
/>
<Person
name={this.state.person[1].name}
age={this.state.person[1].age}
changed={this.changeMethod}
/>
<Person
name={this.state.person[2].name}
age={this.state.person[2].age}
/>
</div>
);
}
return (
<div>
<button onClick={this.changeTxt}>Click here</button>
{person}
</div>
);
}
}
export default App;

If you console.log(showPerson) without setting it. You will see that, its undefined. But after setting it you will see that it has the value. You don't have to initialize them.
Now the reason this code still works is that in javascript there are falsy and truthy values. These values react as true or false values in if statements.
undefined is a falsy value so it pretends like false in if statements. And when you change the value to this: !undefined. Since !falsy === true showPerson becomes true

Your question not clear but from my understanding, your code works and you want to make your code much simple
If so separate you if-else to different function and render it
import React, { Component } from "react";
import "./App.css";
import Person from "./Person/Person";
class App extends Component {
state = {
person: [
{ name: "Andrew", age: 32 },
{ name: "Stephen", age: 42 },
{ name: "Samuel", age: 62 }
]
};
changeTxt = () => {
const doesShow = this.state.showPerson;
this.setState({ showPerson: !doesShow });
};
renderPerson = () => {
if (this.state.showPerson) {
return (
<div>
<Person
name={this.state.person[0].name}
age={this.state.person[0].age}
/>
<Person
name={this.state.person[1].name}
age={this.state.person[1].age}
changed={this.changeMethod}
/>
<Person
name={this.state.person[2].name}
age={this.state.person[2].age}
/>
</div>
)
}else{
return null // your fallback
}
}
render() {
return (
<div>
<button onClick={this.changeTxt}>Click here</button>
{this.renderPerson()}
</div>
);
}
}
export default App;

Related

Working with state on recursive components

I'm writing a component that renders itself inside recursively and is data-driven
Attaching my sandbox snippet, as it will be easier to see there.
This is my data:
var builderStructureData = [
{
id: 123,
value: 3,
children: []
},
{
id: 345,
value: 5,
children: [
{
id: 4123,
value: 34,
children: [
{
id: 342342,
value: 33,
children: []
}
]
},
{
id: 340235,
value: 3431,
children: [
{
id: 342231342,
value: 3415,
children: []
}
]
}
]
}
];
and it renders like this:
This is my App.js:
import { useState } from "react";
import "./App.css";
import Group from "./components/group";
import builderStructureData from "./components/builderStructureData";
function App() {
const [builderStructure, setBuilderStructure] = useState(
builderStructureData
);
return (
<div className="App">
{builderStructure.map((x) => {
return <Group key={x.id} children={x.children} value={x.value} />;
})}
</div>
);
}
export default App;
And this is my recursive component:
import React from "react";
export default function Group(props) {
let childrenArray = [];
if (props.children) {
props.children.map((x) => childrenArray.push(x));
}
return (
<div className="group" draggable>
<p>this is value: </p>
<input value={props.value} readOnly={true}></input>
<button>Add Group</button>
{childrenArray.map((x) => {
return <Group key={x.id} children={x.children} value={x.value} />;
})}
</div>
);
}
I can render the components based on the data, and it seems to be handling recursion fine. I need to store the state on the App.js page and be able to change it from within child components. For example, if I update the "value" field of the component with ID = 342342, I want it to update that corresponding object in the state no matter how deeply nested it is, but not sure how to do that as it is not as simple as just passing a prop.
Am I taking the right approach with my code snippet? How can I do the state update?
I would advise the state normalization approach - here is an example for redux state - https://redux.js.org/usage/structuring-reducers/normalizing-state-shape - but you can use this approach with your state. So - your state will look like this:
state = {
items: {
[123]: {
id: 123,
value: 3,
childrenIds: []
},
[345]: {
id: 345,
value: 5,
childrenIds: [4123, 340235]
},
[4123]: {
id: 4123,
value: 34,
parentId: 345,
childrenIds: [342342]
},
[342342]: {
id: 342342,
value: 33,
parentId: 4123,
childrenIds: []
},
[340235]: {
id: 340235,
value: 3431,
parentId: 345,
childrenIds: [342231342]
},
[342231342]: {
id: 342231342,
value: 3415,
parentId: 340235
childrenIds: []
}
}
}
Here the field "childrenIds" is an optional denormalization for ease of use, if you want - you can do without this field. With this approach, there will be no problem updating the state.
You are thinking this in a wrong way, it should be very easy to do what you want.
The most imported thing is to make a little small changes in Group
Please have a look
import React from "react";
export default function Group(props) {
const [item, setItem] = React.useState(props.item);
let childrenArray = [];
if (item.children) {
item.children.map((x) => childrenArray.push(x));
}
const updateValue = ()=> {
// this will update the value of the current object
// no matter how deep its recrusive is and the update will also happen in APP.js
// now you should also use datacontext in app.js togather with state if you want to
// trigger somethings in app.js
item.value =props.item.value= 15254525;
setState({...item}) // update the state now
}
return (
<div className="group" draggable>
<p>this is value: </p>
<input value={item.value} readOnly={true}></input>
<button>Add Group</button>
{childrenArray.map((x) => {
return <Group item={x} />;
})}
</div>
);
}
The code above should make you understand how easy it is to think about this as an object instead of keys.
Hop this should make it easy for you to understand

Pushing array with useState()

Everyone! i just have this kind of problem that i can`t fix.
this is my App.js
import { useState } from "react"
import Header from "./components/header"
import FeedbackList from "./components/FeedbackList"
import FeedbackData from "./data/FeedbackData"
function App() {
const [feedback, setFeedback] = useState(FeedbackData)
return (
<>
<Header />
<div className="container">
<FeedbackList feedback={feedback} />
</div>
</>
) }
export default App
and this is my second js file that i want to use "feedback" prop like array
import FeedbackItem from "./FeedbackItem"
import FeedbackData from "../data/FeedbackData"
function FeedbackList(feedback) {
return (
<div>
{feedback.map((item)=>(
<FeedbackItem key={item.id} item={item}/>
))}
</div>
)
}
i cant use feedback.map function in this case because feedback is not like array (sorry for my bad english) i solve this problem without using hooks but i want to know what i can do in this case,sorry if im writing something wrong im just new in React and trying to learn.
In Javascript there are object and array. Both can be mapped.
For Array.
const arr = [
{ name: "name 1", id: "01" },
{ name: "name 2", id: "02" },
{ name: "name 3", id: "03" },
];
arr.map(item=> (<div key={item.id}>{item.name}</div>))
For Object.
const obj = {
"item01": { name: "name 1" },
"item02": { name: "name 1" },
"item03": { name: "name 1" },
};
Object.keys(obj).map((key)=> <div key={key}>{obj[key].name}</div>)
Check your type, console.log(typeof FeedbackData).
If it is not type error. Instead of
const [feedback, setFeedback] = useState(FeedbackData)
Try this.
const [feedback,setFeedback] = useState([])
useEffect(()=> setFeedback(FeedbackData),[])
what you want is to destructure the prop you need from the 'props' object.
function Component1() {
const [val, setVal] = useState([]);
return <Component2 val={val} />
}
function Component2({ val }) {
return val.map...
}
this is equivalent to doing:
function Component2(props) {
return props.val.map...
}
this is because props is an object, and so you need to get the right key from the object based on the prop name, either by destructuring or accessing it via props.propName

Property 'map' of undefined in React

I'm learning a react course online. When I try to display the list of items from an array using map to display in a child component , I keep getting "cannot read property map of undefined.
Error is thrown while fetching data from users
import React, { Component } from "react";
import ReactDOM from "react-dom";
let userList = [
{ name: "John", age: 24, place: "India" },
{ name: "Henry", age: 24, place: "India" },
{ name: "Ulrich", age: 24, place: "India" }
];
const AppChild = ({ name, age, place, Graduated }) => {
return (
<section>
<p>name: {name}</p>
<p>age: {age}</p>
<p>place: {place}</p>
{/* access the value via props */}
<p>Graduated: {Graduated ? "yes!" : "no!"}</p>
</section>
);
};
export default class App extends Component {
state = {
userExists: true,
isGraduated: true,
loading: true,
};
toggleStatus = () => {
this.setState(prevState => ({
userExists: !prevState.userExists // value : false
}));
};
render() {
const { users } = this.props;
return (
<div>
<h2>Profile</h2>
<h4>
Profile Status is {this.state.userExists ? "Updated" : "Outdated"}
<br />
<button onClick={this.toggleStatus}>Check Status</button>
</h4>
{users.map(user => (
<AppChild
name={user.name}
age={user.age}
place={user.place}
Graduated={this.state.isGraduated} // passing state to child component
/>
))}
</div>
);
}
}
ReactDOM.render(<App users={userList} />, document.getElementById("root"));
To figure out the problem, we follow the bouncing ball. From the error message, I guess that the problem occurs on the line
{users.map(user => (
(You can confirm this from the stack trace given with the error message.)
The error tells you that users is undefined. So we look at the declaration for users:
const { users } = this.props;
Ok, so it is really this.props.users. So we look where this is passed in:
ReactDOM.render(<App users={userList} />, document.getElementById("root"));
Here you are passing the value of userList to a prop named users. However, in the code you show here, there is no variable named userList. This is as far as we can go with the information you have given. You need to find where this variable is declared and initialized to continue solving the problem.
Below is the correct code. In the previous code I was trying to render <App/> in both index.js and App.js. Thanks everyone for helping me out
=>index.js
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
let userList = [
{ name: "John", age: 24, place: "India" },
{ name: "Henry", age: 24, place: "India" },
{ name: "Ulrich", age: 24, place: "India" }
];
ReactDOM.render(<App users={userList} />, document.getElementById("root"));
=> App.js
import React, { Component } from "react";
// child component
const AppChild = ({ name, age, place, Graduated }) => {
return (
<section>
<p>name: {name}</p>
<p>age: {age}</p>
<p>place: {place}</p>
{/* access the value via props */}
<p>Graduated: {Graduated ? "yes!" : "no!"}</p>
</section>
);
};
// parent component
export default class App extends Component {
state = {
userExists: true,
isGraduated: true,
loading: true,
};
toggleStatus = () => {
this.setState(prevState => ({
userExists: !prevState.userExists // value : false
}));
};
render() {
const { users } = this.props;
return (
<div>
<h2>Profile</h2>
<h4>
Profile Status is {this.state.userExists ? "Updated" : "Outdated"}
<br />
<button onClick={this.toggleStatus}>Check Status</button>
</h4>
{users.map((user) => {
return(
<AppChild
name={user.name}
age={user.age}
place={user.place}
Graduated={this.state.isGraduated} // passing state to child component
/>
)})}
</div>
);
}
}
If you try to log users after following line of code
const { users } = this.props;
you'll see users is undefined.
Error message "cannot read property map of undefined" says the same thing, you can not apply map helper on an undefined variable. The map works with arrays

Creating HTML tag in react component

I'm not extending component class, trying to use usestate to manage state. Now I want to add a person component on certain conditions to personList variable inside the method togglePersonsHanler.
I'm expecting a list of HTML tags to be added like
<person name="person1" age=31>
<person name="person2" age=26>
<person name="person3" age=35>
but on console log, I'm getting personList as below
{$$typeof: Symbol(react.element), type: "div", key: null, ref: null, props: {…}, …}$$typeof: Symbol(react.element)type: "div"key: nullref: nullprops: {children: Array(3)}_owner: null_store: {validated: false}_self: null_source: {fileName: "D:\data\react\my-app\src\App.js", lineNumber: 72, columnNumber: 7}
and person tag is not getting added to DOM, any advice, please
import React, { useState } from 'react';
import './App.css';
import Person from './Person/Person';
const App = props => {
const [personState, setPersonState] = useState({
persons: [
{name: "person1", age:31},
{name: "person2", age:26},
{name: "person3", age:25}
],
other: "some Other Value"
} );
const [otherState,setOtherState]=useState({otherState :'some other value'});
const [showPersonsState,setShowPersonsState]=useState({showPersons :false});
let personList=null;
const togglePersonsHanler =() =>{
personList=null;
setShowPersonsState(
{showPersons : !showPersonsState.showPersons}
)
console.log(showPersonsState.showPersons);
if(showPersonsState.showPersons){
personList=(
<div>{personState.persons.map (person =>{
return <person name={person.name} age={person.age}/>
}
)}</div>
);
}
console.log(personList);
}
return (
<div className="App">
<h1> HI, I'm the react app</h1>
<button
//onClick={switchNameHandler.bind(this,'Gopu Ravi')}
onClick={togglePersonsHanler}
style={style}> Toggle Person </button>
{ personList }
</div>
);
}
export default App;
You're mapping the object literals by using them as an html tag. You likely meant to use the imported Person component.
<div>
{personState.persons.map (person => (
<Person name={person.name} age={person.age}/>
)}
</div>
And to fix a react-key warning since all mapped elements need unique keys, add a key prop with a value that is unique to the data in the array, like name:
<div>
{personState.persons.map (person => (
<Person key={name} name={person.name} age={person.age}/>
)}
</div>
To correctly toggle the display of the "personList":
Conditionally render the mapped persons array if showPersonsState is true
Simplify showPersonsState state to simply be the boolean value
Use functional state update to correctly toggle showPersonsState from previous state
Updated component code
const App = props => {
const [personState, setPersonState] = useState({
persons: [
{ name: "person1", age: 31 },
{ name: "person2", age: 26 },
{ name: "person3", age: 25 }
],
other: "some Other Value"
});
const [otherState, setOtherState] = useState({
otherState: "some other value"
});
const [showPersonsState, setShowPersonsState] = useState(false);
const togglePersonsHandler = () => setShowPersonsState(show => !show);
return (
<div className="App">
<h1> HI, I'm the react app</h1>
<button onClick={togglePersonsHandler}>Toggle Person</button>
{showPersonsState &&
personState.persons.map(({ age, name }) => (
<Person key={`${name}`} name={name} age={age} />
))}
</div>
);
};

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