I'm not able get what I'm doing wrong here. Could someone please help me out here. I'm unable to print the value to the screen. I'm trying to print the value from the state to the screen but I'm unable to.
Its not showing any error. I know this could be a silly mistake. Please help me out. Thanks
I'm not able get what I'm doing wrong here. Could someone please help me out here. I'm unable to print the value to the screen. i'm trying to print the value from the state to the screen but i'm unable to.
Its not showing any error.
import React, { Component } from "react";
import "./Screen.css";
export default class Screen extends Component {
constructor(props) {
super(props);
this.state = {
roles: [
{ id: 1, value: "Contracts manager", isChecked: false },
{ id: 2, value: "In-house counsel", isChecked: false },
{ id: 3, value: "IT administrator", isChecked: false },
{ id: 4, value: "Law clerk", isChecked: false },
{ id: 5, value: "Legal administrator", isChecked: false },
{ id: 6, value: "Legal operations manager", isChecked: false },
{ id: 7, value: "Legal secretary", isChecked: false },
{ id: 8, value: "Paralegal", isChecked: false },
{ id: 9, value: "Procurement manager", isChecked: false },
{ id: 10, value: "Solicitor", isChecked: false },
{ id: 11, value: "Other", isChecked: false },
],
aksha: "aksk",
};
console.log(this.state);
}
roleHandler = (event) => {
let roles = this.state.roles;
roles.forEach((role) => {
if (role.value === event.target.value)
role.isChecked = event.target.checked;
});
this.setState({ roles: roles });
};
render() {
const newRoles = this.state.roles.map((role) => {
return (
<div className="border-inp">
<label className="checkbox">
<span className="checkbox__input">
<input
type="checkbox"
name="checkbox"
key={this.state.roles.id}
onClick={this.roleHandler}
value={this.state.roles.value}
checked={this.state.roles.checked}
/>{" "}
{this.state.roles.value}
</span>
</label>
</div>
);
});
return (
<div>
<div className="Screenbg">
<div id="viewport" className="screenview">
<h3 className="wel">Welcome</h3>
<div>
<h5 className="role">What is your role?</h5>
{newRoles}
</div>
<div className="grid-container btndiv">
{/* <div className="grid-child purple">
<button className="btn">Back</button>
</div> */}
<div className="grid-child green">
{/* <Link to="/"> */}
<button className="btn">Next</button>
{/* </Link> */}
</div>
</div>
</div>
</div>
</div>
);
}
}
role must be used for rendering your array. You were using state to get it.
render() {
const newRoles = this.state.roles.map((role) => {
return (
<div className="border-inp">
<label className="checkbox">
<span className="checkbox__input">
<input
type="checkbox"
name="checkbox"
key={this.state.roles.id}
onClick={this.roleHandler}
value={this.state.roles.value}
checked={this.state.roles.checked}
/>
{role.value}
</span>
</label>
</div>
Related
I am trying to add onClick function to this array. So when i click on "How will i get cashback?",output
it must display the items(Page Page One,Two) image and when i click on "Page Page One", it must display "Subcontent"
stackblitz
export default class Chat extends React.Component {
constructor(props) {
super(props);
this.state = {
message: [
{
id: 1,
title: "How will i get cashback?",
items: [
{
id: 1,
title: "Page Page One",
items: [
{
id: 1,
title: 'SubContent'
}
],
},
{
id: 2,
title: "Two",
},
],
},
{
id: 2,
title: "Reschedule delivery",
items: [],
},
],
};
}
render() {
const { message } = this.state;
return (
<div>
<p className={styles.titleText}>AAAAAA</p>
<div className={styles.line} />
{message.map((m) => (
<div>
<div
className={styles.button}
>
{m.title}
<i
className={`fa fa-chevron-right`}
aria-hidden="true"
/>
</div>
<div className={styles.line} />
</div>
))}
</div>
);
}
}
Add this change to your code.
Basically what you are telling your program is "If I have items, then set the state to be these items, else do nothing"
<div className={`button`} onClick={() => m.items ? this.setState({ message: m.items }) : null}>
{m.title}
<i className={`fa fa-chevron-right`} aria-hidden="true" />
</div>
i'm using map to loop trough an array and then fill a div with it, but it's always empty:
Here's some of my code:
const [scoreOptions, setScoreOptions] = useState(initialScoreOption);
const initialScoreOption = [
{ id: 1, selected: false, icon: 'far fa-smile', label: 'lala'},
{ id: 2, selected: false, icon: 'far fa-meh', label: 'lalala'},
{ id: 3, selected: false, icon: 'far fa-frown', label: 'lalala'}
];
let iconosTexto;
if (scoreOptions){
iconosTexto = scoreOptions.map(icono => {
return(
<div className="contenedorIconoTexto">
<div className="iconoElemento">
<i className={blue ? `blueIcon ${icono.icon}` : `greyIcon ${icono.icon}`}>
</i>
</div>
<div className="iconoTexto">
{icono.label}
</div>
</div>
)
});
}
and then i have this on the render
<div className="container">
{ iconosTexto }
</div>
The div with the class container it's empty when it should be filled with all of the above
Can anyone help me with this?
Firstly, declare initialScoreOption before useState(initialScoreOption).
Use set key prop while rendering elements in map:
iconosTexto = scoreOptions.map((icono) => {
return (
<div key={icono.id} className="contenedorIconoTexto">
...
Then make sure that iconosTexto has always value.
Try this way :
const IconosTexto = () => scoreOptions.map(icono => {
return (
<div className="contenedorIconoTexto">
<div className="iconoElemento">
<i className={blue ? `blueIcon ${icono.icon}` : `greyIcon ${icono.icon}`}
>
</i>
</div>
<div className="iconoTexto">{icono.label}</div>
</div>
)
}
render (
<div className="container">
<IconosTexto />
</div>
)
You need to declare initialScoreOption before passing it to useState:
const initialScoreOption = [
{ id: 1, selected: false, icon: 'far fa-smile', label: 'lala'},
{ id: 2, selected: false, icon: 'far fa-meh', label: 'lalala'},
{ id: 3, selected: false, icon: 'far fa-frown', label: 'lalala'}
];
const [scoreOptions, setScoreOptions] = useState(initialScoreOption);
demo
I have several checkbox groups on my Component of which only one of the should be selected. Each group has the same number of checkboxes (3 in the example), and the one selected is identified by the checked key inside the data list.
How can I handle this state?
class test extends Component {
constructor(props) {
super(props);
this.state = {};
const data = [
{ name: orange, checked: 2 },
{ name: apple, checked: 3 },
{ name: banana, checked: 1 }
];
}
render() {
return (
<>
{data.map(items => (
<tr>
<td>{items.name}</td>
<td>
<div>
<input type="checkbox" value="1" checked={true} />
</div>
</td>
<td>
<div>
<input type="checkbox" value="2" checked={false} />
</div>
</td>
<td>
<div>
<input type="checkbox" value="3" checked={false} />
</div>
</td>
</tr>
))}
</>
);
}
}
Try organizing your data-structure to look something like this:
data: [
{ name: "orange", boxes: [1, 2, 3], selected: null },
{ name: "apple", boxes: [1, 2, 3], selected: null },
{ name: "pineapple", boxes: [1, 2, 3], selected: null }
]
That gives us a group-name, an array of values to choose from and a selected value.
We'll be manipulating that data via our component-state.
Here's a codesandbox for reference: https://codesandbox.io/s/gallant-paper-b1d4z
Working code:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{ name: "orange", boxes: [1, 2, 3], selected: null },
{ name: "apple", boxes: [1, 2, 3], selected: null },
{ name: "pineapple", boxes: [1, 2, 3], selected: null }
]
};
}
handleOnChange = e => {
const { data } = this.state;
const { name, value } = e.target;
const updatedData = data.map(group => {
if (group.name === name) {
return {
...group,
selected: group.selected === value ? null : value
};
} else {
return group;
}
});
this.setState({ data: updatedData }, () => console.log(this.state));
};
createInputGroups = () => {
const { data } = this.state;
const groups = data.map(group => {
return (
<div style={{ display: "flex" }}>
<div>{group.name}</div>
<div>
{group.boxes.map(box => {
return (
<input
onChange={this.handleOnChange}
type="checkbox"
name={group.name}
value={box}
checked={group.selected == box}
/>
);
})}
</div>
</div>
);
});
return groups;
};
render() {
return <div>{this.createInputGroups()}</div>;
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Pleases excuse my CSS :)
You can check at the checked option if the value of the checkbox is the same as the checked value of your item interface. Check this component as an example:
function CheckboxGroupRow({ name, checked, onUpdate }) {
return (
<tr className="CheckboxGroup">
<td>{name}</td>
<td>
<input
type="checkbox"
value={1}
checked={checked === 1}
onChange={e => onUpdate({ name, checked: +e.target.value })}
/>
</td>
<td>
<input
type="checkbox"
value={2}
checked={checked === 2}
onChange={e => onUpdate({ name, checked: +e.target.value })}
/>
</td>
<td>
<input
type="checkbox"
value={3}
checked={checked === 3}
onChange={e => onUpdate({ name, checked: +e.target.value })}
/>
</td>
</tr>
);
}
Each checkbox has a value, and it's checked only if the value of the checked variable matches to the one on the checkbox. For the onChange handle I have an onUpdate function that will be called with an updated data item whenever a user clicks a checkbox. Some logic upstream should handle the update.
Please take a look at this example build on CodeSandbox:
https://codesandbox.io/embed/checkboxgroup-cyv4p
I hope it helps
I would like to display a certain RSS feed depending on what item you select from the dropdown menu. At the minute when I select the item it will display the link on the screen but it will not update the state.
import React, { Component } from 'react'
class FacebookRSSDropdown extends Component {
state = {
links: [{id: 1, name: "Lost and Found Pets Northern Ireland" , content: "https://www.facebook.com/PetsLostandFoundNorthernIreland/"},
{id: 2, name: "USPCA", content: "https://www.facebook.com/UlsterSPCA/"},
{id: 3, name: "Pawboost Northern Ireland", content: "https://www.facebook.com/Northern-Ireland-Lost-Dogs-Cats-Pets-147512902479398/"},
{id: 4, name: "Assisi Animal Sanctuary", content: "https://www.facebook.com/AssisiAnimalSanctuary/"},
{id: 5, name: "Pets Reunited Newry and Mourne", content: "https://www.facebook.com/PetsReunitedNewryAndMourne/"}
],
linkClicked: [{
content: ''
}]
}
handleChange = (e) => {
console.log(e.target.value);
this.setState({
linkClicked: e.target.value
})
}
render() {
return (
<div className="container-fluid">
<h1> Facebook RSS Feeds </h1>
<select className="form-control" onClick={this.handleChange}>
{this.state.links && this.state.links.map(link => {
return (
<option value={link.content}>{link.name}</option>
)
})}
</select>
<div id="rssfeeds" className="row">
<div className="col">
<div className="fb-page"
data-tabs="timeline,events,messages"
data-href={this.state.linkClicked.content}
data-width="500"
data-height="850"
data-hide-cover="false">
</div>
</div>
</div>
</div>
)
}
}
export default FacebookRSSDropdown
For a <select> you should register a listener for onChange rather than onClick
handleChange = ev => {
this.setState({
linkClicked: ev.target.value
})
}
<select className="form-control" onChange={this.handleChange}>
The code below displays three Election Contestants from the arrays.
Now I want to show their vote counts for each contestanst based on their Ids.
here is the arrays showing various contestant results that i want to merge based on their Id's
contestantResult: [
{ id: 1, voteCount: "500 Votes" },
{ id: 2, voteCount: "200 Votes" },
{ id: 3, voteCount: "320 votes" },
],
My issues is stated below:
Each time I run the code, all the three contestant are seen having 500 votes but in reality based on their Ids,
Contestant 1 should have 500 votes.
Contestant 2 should have 200 votes.
Contestant 3 should have 320 votes.
I guess I have to loop through the contestant Vote results arrays using something like map() functions as per the code below but do not know
how to apply it. Any help or solutions will be appreciated
{this.state.contestantResult.map((contestant, i) => {
//if (contestant.id == person.id) {
if (contestant.id) {
return (
<div key={i}>
<div>{contestant.voteCount}</div>
</div>
);
}
})}
Below is my coding efforts so far
import React, { Component, Fragment } from "react";
import { render } from "react-dom";
class Contestant extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<React.Fragment>
<div key={this.props.data.id}>
<div style={{ background: "black", color: "white" }}>
<b>Id:</b>
{this.props.data.id}
<br />
<b>Name:</b> {this.props.data.name}
<br />
<b style={{ color: "red" }}>Vote Count: {this.props.resultVotes}</b>
<br />
</div>
</div>
</React.Fragment>
);
}
}
class VoteResult extends React.Component {
constructor() {
super();
this.state = {
data: [
{ id: 1, name: "contestant 1" },
{ id: 2, name: "contestant 2" },
{ id: 3, name: "contestant 3" }
],
contestantResult: [
{ id: 1, voteCount: "500 Votes" },
{ id: 2, voteCount: "200 Votes" },
{ id: 3, voteCount: "320 votes" }
]
};
}
componentDidMount() {}
render() {
return (
<div>
<h1> Electoral College Voting......</h1>
{this.state.data.map(person => {
return (
<Contestant
key={person.id}
data={person}
resultVotes={this.state.contestantResult[0].voteCount}
/>
);
})}
</div>
);
}
}
You don't want to take the first object in the contestantResult array for every iteration in the loop. You could instead use find to find the result of the correct contestant.
{this.state.data.map(person => {
const result = this.state.contestantResult.find(res => res.id === person.id);
return (
<Contestant
key={person.id}
data={person}
resultVotes={result.voteCount}
/>
);
})}
class VoteResult extends React.Component {
state = {
data: [
{ id: 1, name: "contestant 1" },
{ id: 2, name: "contestant 2" },
{ id: 3, name: "contestant 3" }
],
contestantResult: [
{ id: 1, voteCount: "500 Votes" },
{ id: 2, voteCount: "200 Votes" },
{ id: 3, voteCount: "320 votes" }
]
};
render() {
const { data, contestantResult } = this.state;
return (
<div>
<h1> Electoral College Voting......</h1>
{data.map(person => {
const result = contestantResult.find(res => res.id === person.id);
return (
<Contestant
key={person.id}
data={person}
resultVotes={result.voteCount}
/>
);
})}
</div>
);
}
}
class Contestant extends React.Component {
render() {
return (
<div key={this.props.data.id}>
<div style={{ background: "black", color: "white" }}>
<b>Id:</b>
{this.props.data.id}
<br />
<b>Name:</b> {this.props.data.name}
<br />
<b style={{ color: "red" }}>Vote Count: {this.props.resultVotes}</b>
<br />
</div>
</div>
);
}
}
ReactDOM.render(<VoteResult />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>