REACT: Add highlighted border around selected image [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want a border around the picture when I select it. So if I have 6 pictures and choose 3, I would like to have highlighted borders around those images. Question is,How can I do this? EDIT: I am using React for this dilemma.

This depends on how you want to track state in your app.. here is an example which tracks the state in the parent component. Essentially you have a single parent App component which tracks the state for each image, and then an Image component which renders either with or without a border, depending on a piece of the App state which gets passed down as a prop. Refer to the code to see what I mean. An alternative would be to have the active state live within each Image component itself.
The code has a number of interesting features mainly due to leveraging several aspects of ES6 to be more concise, as well as React's immutability helper to help update the state array in an immutable way, and lodash's times method to assist in creating our initial state array.
Code (some of the indenting got a bit muddled in the copy from jsfiddle..):
function getImage() {
return { active: false };
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { images: _.times(6, getImage) };
this.clickImage = this.clickImage.bind(this);
}
clickImage(ix) {
const images = React.addons.update(this.state.images, {
[ix]: { $apply: x => ({ active: !x.active}) }
})
this.setState({ images });
}
render() {
const { images } = this.state;
return (
<div>
{ images.map((image, ix) =>
<Image
key={ix}
ix={ix}
active={image.active}
clickImage={this.clickImage} />) }
</div>
);
}
};
class Image extends React.Component {
render() {
const { ix, clickImage, active } = this.props;
const style = active ? { border: '1px solid #021a40' } : {};
return <img
style={style}
src={`https://robohash.org/${ix}`}
onClick={() => clickImage(ix)}/>;
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
);
And then what it looks like:

Just add an event handler for click that adds a "selected" class, then set that selected class to have a border in css.
.selectableImg {
border: solid 1px transparent;
margin: 10px;
}
.selectableImg.selected {
border: solid 1px blue;
}
<img class="selectableImg" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
<img class="selectableImg" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
<img class="selectableImg" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
<img class="selectableImg" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
<script>
var images = document.querySelectorAll(".selectableImg");
images.forEach(function(i) {i.addEventListener("click", function(event) {
i.classList.toggle("selected");
})});
</script>

Related

Change component characteristics (style) using a loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Is there anyway to go through each component(Ex: button/label) characteristics using an infinite loop? In my app I have 24 buttons in a particular screen and I want to change color of each button one by one all the time. I want to change the color of each button one by one all the time. I have tried both componentdidmount and componentwillmount, but it happens once. When I go to another screen and come back, the loop doesnt start.
If you want to do this on a timed interval, you'd keep track of the selected item in your state, e.g.:
// In your constructor (since you mentioned `componentDidMount`, I know you're using classes)
this.state = {
selectedControl: 0,
// ...your other state
};
In componentDidMount, start your interval timer:
componentDidMount() {
this.timerHandle = setInterval(() => {
this.setState(({selectedControl, controls}) =>
({selectedControl: (selectedControl + 1) % controls.length})
);
}, 2000); // 2000ms = two seconds
}
When rendering the controls, highlight the selected one:
render() {
const {selectedControl, controls} = this.state;
return (
<div>
{controls.map((control, index) => (
<input key={index} type="button" value={control} className={index === selectedControl ? "highlighted" : undefined} />
))}
</div>
);
}
Note that in all of that I've assumed this.state.controls is an array of your controls.
Adjust as necessary, that's just to get you headed the right way.
Live Example (going a bit faster than 2 seconds):
class Example extends React.Component {
constructor(props) {
super(props);
// In your constructor (since you mentioned `componentDidMount`, I know you're using classes)
this.state = {
selectedControl: 0,
controls: ["one", "two", "three", "four"]
};
}
componentDidMount() {
this.timerHandle = setInterval(() => {
this.setState(({selectedControl, controls}) =>
({selectedControl: (selectedControl + 1) % controls.length})
);
}, 800); // 800ms = 0.8 seconds
}
render() {
const {selectedControl, controls} = this.state;
return (
<div>
{controls.map((control, index) => (
<input key={index} type="button" value={control} className={index === selectedControl ? "highlighted" : undefined} />
))}
</div>
);
}
}
ReactDOM.render(<Example />, document.getElementById("root"));
.highlighted {
font-weight: bold;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.development.js"></script>

Reactjs : How I can change button style when clicked [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am new to ReactJS, Currently I am using ant.design for my interface and In ant.design I am using Switch Steps for Wizard form. I want to change Next Button style when clicked . I am new to this platform please guide me
Thanks
So to change the loading state you can modify the example in the docs to be:
import { Steps, Button, message } from 'antd';
const Step = Steps.Step;
const steps = [{
title: 'First',
content: 'First-content',
}, {
title: 'Second',
content: 'Second-content',
}, {
title: 'Last',
content: 'Last-content',
}];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
current: 0,
loading: false
};
}
next() {
const current = this.state.current + 1;
this.setState({ current, loading: true });
}
prev() {
const current = this.state.current - 1;
this.setState({ current });
}
render() {
const { current, loading } = this.state;
return (
<div>
<Steps current={current}>
{steps.map(item => <Step key={item.title} title={item.title} />)}
</Steps>
<div className="steps-content">{steps[current].content}</div>
<div className="steps-action">
{
current < steps.length - 1
&& <Button type="primary" loading={loading} onClick={() => this.next()}>Next</Button>
}
{
current === steps.length - 1
&& <Button type="primary" loading={loading} onClick={() => message.success('Processing complete!')}>Done</Button>
}
{
current > 0
&& (
<Button loading={loading} style={{ marginLeft: 8 }} onClick={() => this.prev()}>
Previous
</Button>
)
}
</div>
</div>
);
}
}
This will cause the button to go into loading state when Next is clicked. However you need some external event that is fed into the component to tell it when to remove the loading state.
This can be done by having a this.prop that is changed from the parent component and detected in componentWillReceiveProps, where you do this.setState({loading:false}), or by making next() call some asynch method which resets the loading state in its callback.

Having trouble managing states in Reactjs

I have been practicing JavaScript and ReactJs and I have been stuck on a problem for a while. Basically, I am trying to rewrite my HTML, CSS, Javascript project using ReactJs.
Here is my problem: (in regards to the React code). Say I click on the first answer choice for Question 1, the class name changes hence, styling changes(background becomes black) AND isClicked becomes true (both are states inside the EachIndividualAnswer class). If I then click on the second answer choice, I want the style for the first answer choice (and every other answer choice for that question) to be null, and isClicked to be false and ONLY the second answer will have isClicked === true and className="clicked".
Hope this makes sense. Sorry for sending so many files, Didn't know any other way.
Thanks
MY HTML, CSS AND JAVASCRIPT CODE. (the code I am trying to re-write with ReactJs)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
var numberOfQuestions = 5;
var choicesPerQuestion = 5;
var questionNumber = document.getElementsByClassName("questionNumber");
var question = document.getElementsByClassName("question");
var answers = document.getElementsByClassName("answers");
var answer_A = document.getElementsByClassName("answer_A");
var answer_B = document.getElementsByClassName("answer_B");
var answer_C = document.getElementsByClassName("answer_C");
var answer_D = document.getElementsByClassName("answer_D");
var answer_E = document.getElementsByClassName("answer_E");
var submit = document.getElementById("submit");
// Answer key
var answerKey = [21, 3, "Nani", "Kevin Durant", "Russ"];
var userAnswerArray = new Array(5);
// Put every single possible clickable answer in 5x5 array
// clicking an answer changes its background and color
var individual_answers = new Array(numberOfQuestions);
for(let i=0; i<numberOfQuestions; i++) {
individual_answers[i] = new Array(choicesPerQuestion);
}
// Adding Event listeners to each answer choice
for (let i = 0; i < answers.length; i++) {
specificAnswers = answers[i].getElementsByTagName("li"); // answers to each questions e.g. answers to qu.1, then qu.2
for (let j = 0; j < specificAnswers.length; j++) {
individual_answers[i][j] = specificAnswers[j]; // individual answers to each qu.
var spanX = individual_answers[i][j].getElementsByTagName("span"); // did not use this
individual_answers[i][j].addEventListener("click", click(i , j));
}
}
function click(i, j) {
return function() {
console.log(individual_answers[i][j].innerText);
if(individual_answers[i][j].style.background != "black") { // if it's not black, set all to white, then put specific one to black
for(let x=0; x<choicesPerQuestion; x++) {
individual_answers[i][x].style.cssText = "background: white";
individual_answers[i][x].getElementsByTagName("span")[0].style.color = "black";
}
individual_answers[i][j].style.cssText = "background: black";
individual_answers[i][j].style.color = "green";
individual_answers[i][j].getElementsByTagName("span")[0].style.color = "white";
userAnswerArray[i] = individual_answers[i][j].innerText;
// i = question number, j = specific answer to question number i
// So on each click, if answer originally doesn't have a black background, add it to userArray
}
else { // If background is black, on click you have to remove that from individual array
individual_answers[i][j].style.cssText = "background: white";
individual_answers[i][j].getElementsByTagName("span")[0].style.color = "black";
userAnswerArray.splice(i, 1);
}
}
}
// Adding event listener to submit button
submit.addEventListener("click", score);
/* Easiest thing to do would be to make an "Answer class" for each answer. (using prototypes) with field selected.
Then count the number of answers with fields selected and compare with answer key or smthn. Try this as an exercise for later, maybe ReactJs */
/* For now I will create an array for the answers that will change as the user clicks and use the actual words to see if they match */
function score() {
/* Add a check later to see if he has answered every question or at least 60% */
var counter = 0;
for(let x=0; x<numberOfQuestions; x++) {
if(answerKey[x] == userAnswerArray[x]) {
counter++;
}
}
console.log("User has submitted the quiz and scored " + counter);
if(counter < 3) {
alert("Try again, you failed");
}
else {
alert("Are you a lizard?")
}
/* Show on a message and ask to retake*/
}
ul {
list-style-type: square;
}
ul > li {
color: blue;
font-size: 30px;
}
ul > li > span {
color: black;
font-size: 20px;
}
#submit {
font-size: 30px;
}
<!--I will try to create a multiple choice exam. The user can NOT submit until he has answered 60% of the questions. Once he submits
I will show him his score. Give him the option to see which questions he failed, as well as the right answer. -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Multiple Choice Exam</title>
<link rel="stylesheet" href="mcq.css">
</head>
<body>
<h1>NASA Final Entry Exam</h1>
<h2>Only the most genius of individuals will pass</h2>
<br>
<hr>
<br>
<p class="question"><span class="questionOne">1</span>. What is 9+10</p>
<ul class="answers" id="answers1">
<li class="answer_A"><span>1</span></li>
<li class="answer_B"><span>19</span></li>
<li class="answer_C"><span>21</span></li>
<li class="answer_D"><span>90</span></li>
<li class="answer_E"><span>-1<span></li>
</ul>
<p class="question"><span class="questiontwo">2</span>. How many goals did Ronaldo score against Spain in the World Cup 2018</p>
<ul class="answers">
<li class="answer_A"><span>1</span></li>
<li class="answer_B"><span>3</span></li>
<li class="answer_C"><span>5</span></li>
<li class="answer_D"><span>0</span></li>
<li class="answer_E"><span>-1<span></li>
</ul>
<p class="question"><span class="questionThree">3</span>. Who Stole Ronaldo's (CR7) greates ever goal?</p>
<ul class="answers">
<li class="answer_A"><span>Pepe</span></li>
<li class="answer_B"><span>Messi</span></li>
<li class="answer_C"><span>Casillas</span></li>
<li class="answer_D"><span>Benzema</span></li>
<li class="answer_E"><span>Nani<span></li>
</ul>
<p class="question"><span class="questionFour">4</span>. Which one of these players ruined the NBA</p>
<ul class="answers">
<li class="answer_A"><span>Allen Iverson</span></li>
<li class="answer_B"><span>Kevin Durant</span></li>
<li class="answer_C"><span>Steph Curry</span></li>
<li class="answer_D"><span>Lebron James</span></li>
<li class="answer_E"><span>Russel Westbrook<span></li>
</ul>
<p class="question"><span class="questionFive">5</span>. Who is currently number 1 in the internet L ranking?</p>
<ul class="answers">
<li class="answer_A"><span>Drake</span></li>
<li class="answer_B"><span>Pusha T</span></li>
<li class="answer_C"><span>Russel WestBrook</span></li>
<li class="answer_D"><span>Lil Xan</span></li>
<li class="answer_E"><span>Russ<span></li>
</ul>
<button id="submit">Submit</button>
<script src="mcq.js"></script>
</body>
</html>
HERE IS MY REACJS PROJECT SO FAR. Wasn't sure on how to properly upload these files:
[App.js]
import React, { Component } from 'react';
import './App.css';
import Title from './Title/Title';
import Question from './Question/Question';
import Aux from './hoc/Aux';
class App extends Component {
state = {
counter: 0,
questionArray: [
"What is 9+10",
"How many goals did Ronaldo score against Spain in the World Cup 2018",
"Who Stole Ronaldo's (CR7) greates ever goal?",
"Which one of these players ruined the NBA",
"Who is currently number 1 in the internet L rankings?"
],
answerChoicesArray: [
["1", "19", "21", "90", "-1"],
["1", "3", "5", "0", "-1"],
["Pepe", "Messi", "Casillas", "Benzema", "Nani"],
["Allen Iverson", "Kevin Durant", "Steph Curry", "Lebron James", "Russel Westbrook"],
["Drake", "Pusha T", "Russel Westbrook", "Lil Xan", "Russ"]
]
}
render() {
return (
<div className="App">
<div className="container">
<Aux>
<Title />
<h2>Only the most genius of individuals will pass</h2>
<hr/>
<Question
questionArray={this.state.questionArray}
answerChoicesArray={this.state.answerChoicesArray} />
<button
onClick={() => alert("We don't support this yet")}
type="submit">SUBMIT</button>
</Aux>
</div>
</div>
);
}
}
export default App;
.
.
[Question.js]
import React from 'react';
import AnswerChoices from '../AnswersChoices/AnswerChoices';
const Question = (props) => // why doesn't it work if I put a curly brace here
props.questionArray.map((question, index) => {
return(
<div>
<p>{index + 1}. {question}</p>
<AnswerChoices
index={index} // try just index answersArray is the array of ALL answers
answerChoicesArray={props.answerChoicesArray} />
</div>
);
})
export default Question;
.
.
[AnswerChoices.js]
import React from 'react';
import SpecificAnswerChoice from './SpecificAnswerChoice/SpecificAnswerChoice'
const AnswerChoices = (props) => {
console.log(props.answerChoicesArray[props.index]);
return (
// 5 answers array for each question
<div>
<ul>
<SpecificAnswerChoice
answers={props.answerChoicesArray[props.index]}/>
</ul>
</div>
)
}
export default AnswerChoices;
.
.
[SpecificAnswerChoice.js]
import React, { Component } from 'react';
import EachIndividualAnswer from './EachIndividualAnswer/EachIndividualAnswer'
class SpecificAnswerChoice extends Component {
// If I click once, set all to white and specific to black
state = {
resetClicksState: true // can start w/ false then change to always true inside resetClicks function
}
resetClicks = () => {
console.log("TEST");
}
render() {
// const style = {
// backgroundColor: 'white'
// };
return(
this.props.answers.map(individualAnswer => {
return (
<EachIndividualAnswer
className={this.state.class}
individualAnswer={individualAnswer}
resetClicks={this.resetClicks}
// onClick={this.clickHandler}
/>
);
})
)
}
}
export default SpecificAnswerChoice;
import React, { Component } from 'react';
.
.
[EachIndividualAnswer.js]
class EachIndividualAnswer extends Component {
state = {
isClicked: false,
class: ""
}
// clickHandler = (style) => {
// if(style.backgroundColor === 'white') {
// style.backgroundColor = 'black';
// style.color = 'white';
// }
// }
onClickHandler = () => {
console.log(this.state.isClicked);
console.log("djhfdf");
if(this.state.isClicked) {
var tempClass=""
this.setState({
isClicked: false,
class: tempClass
});
} else {
tempClass="clicked"
this.setState({
isClicked: true,
class:tempClass
})
}
this.props.resetClicks();
}
// testingOnClick = () => {
// console.log("If this works then I have 2+ functions on OnClick");
// }
// if props.resetClicks is true, which it always is, className='', isClicked=false for EVERY
// EachIndividualAnswer. Then I do my logc that I already had
render() {
return (<li
className={this.state.class}
onClick={this.onClickHandler}>
<span>
{this.props.individualAnswer}
</span>
</li>);
}
}
export default EachIndividualAnswer;
.
.
[Aux.js]
const aux = (props) => props.children;
export default aux;
Here is one possible answer if I understood you right. I'm totally mimicking the situation so this is not a complete solution for you.
class App extends React.Component {
state = {
answers: [ "1", "19", "21", "90", "-1" ],
selected: {},
}
handleClick = e => {
const {answer} = e.target.dataset;
this.setState({selected:{
[answer]: !!answer,
}})
};
render() {
const {answers} = this.state;
console.log(this.state.selected);
return (
<div>
<ul>
{
answers.map( answer =>
<li
data-answer={answer}
className={
this.state.selected[answer] ? 'colored' : ''
}
onClick={this.handleClick}
>{answer}
</li>
)
}
</ul>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
.colored {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Here, we are using a selected state to hold the selected situation and according to this situation we are adding our class or set it to null. Our handleClick function does this selection change. There is a console.log in the render method so you can see what is going on here.
Also, I used dataset here to get the value since I don't like binding functions in JSX. With .bind it can be like that. Only the relevant parts:
handleClick2 = answer =>
this.setState({
selected: {
[answer]: !!answer,
}
})
and
onClick={this.handleClick2.bind(this, answer)}
One other possible solution to here, instead of doing this logic in your EachIndividualAnswer component you can do it in your SpecificAnswerChoice component. I mean holding the state and having handleClick handler. So, you can pass this handler to your EachIndividualAnswer with the answer than with your callback you can set the state in the EachIndividualAnswer. So, there will be no need to use datasets or .bind.
Lastly, as other says in the comments you should share a minimal code where you have problems. So, people can look your code easily and do their best.
If you think holding long answers as object properties is silly, here is another answer using array indexes of answers:
class App extends React.Component {
state = {
answers: [ "1", "19", "21", "90", "-1" ],
selected: {},
}
handleClick = e => {
const {index} = e.target.dataset;
this.setState({selected:{
[index]: !!index,
}})
};
render() {
const {answers} = this.state;
console.log(this.state.selected);
return (
<div>
<ul>
{
answers.map( (answer, index) =>
<li
data-index={index}
className={
this.state.selected[index] ? 'colored' : ''
}
onClick={this.handleClick}
>{answer}
</li>
)
}
</ul>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
.colored {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Edit after questions in comments
const {answers} = this.state
This is Javascript's destructuring assignment syntax. We are just picking a property from the this.state object. Shorthand version of this code:
const answers = this.state.answers;
At first this could be seem not so useful but you can pick as many property as you want in an object. Think about a crowded object and you just need just three of them:
const { one, two, three } = object;
This is the shorthand of:
const one = object.one;
const two = object.two;
const three = object.three;
Very useful. For further information just read this answer and of course the official documentation. You can see destructring all around React world since some people tend to use where it is suitable. It may not be always so nice when it is overused. It makes harder to read the code sometimes. But when you use it in the suitable places, it saves time and even makes readability better.
We are keeping answers here in our state. In your original code you are getting them as props. I will provide another answer after doing the explanation based on props. selected is the real deal here, state that we keep our selected elements.
this.setState({selected:{ [answer]: !!answer }})
Yes, this is a little bit awkward. We are using computed property for objects. So, we can use variables in an object's property. [answer], this is what we use. So, in the selected state we are setting a property which name is our answer variable. Now, we use the right hand side to use our value to a boolean and we are setting it always to true in the first state change.
answer variable is a string here. In Javascript if you use logical not, ! , operator on a string it evaluates to false. So we are using it twice to get true. For example, when we click on "19" this would be like this:
selected: {
"19": !!"19"
}
You can try !!"19" in Javascript console, you will get true. Instead of using real values, we are just using variables here: [answer]: !!answer
Now, I will change this syntax a little bit in my last code example. If you look setState's documentation you will see it is an asynchronous operation. So, React team discourages us to use it directly like this, especially if we use previous state of any piece in our state. Actually we are not doing it like that in our example but it is better using a callback for this.setState. Please go and read official documentation if this explanation is not enough for you. Here how we use it this time:
handleClick = answer => {
this.setState(prevState =>
({
selected: {
[answer]: !prevState.selected.answer,
}
})
)
};
As you can see setState here takes a callback and uses prevState (or what name you give it) to react the previous state. Now, since there is not any selected.answer in our previous state, it is undefined in the first place. So, we can use !prevState.selected.answer to make the value true instead of using two logical not operand here. Remember, in the previous example we have a string here not an undefined value. This is why we use two logical not operand there.
Now, here is the last code that suits your situation. You are getting answers as prop and then render another component to show those. I use three components like you then render the individual answers.
const answers = ["1", "19", "21", "90", "-1"]
const AnswerChoices = () => (
<SpecificAnswerChoice answers={answers} />
)
class SpecificAnswerChoice extends React.Component {
state = {
selected: {},
}
handleClick = answer =>
this.setState(prevState =>
({
selected: {
[answer]: !prevState.selected.answer,
}
})
);
render() {
const { answers } = this.props;
return (
<div>
{
answers.map( individualAnswer => (
<EachIndividualAnswer
individualAnswer={individualAnswer}
onClick={this.handleClick}
selected={this.state.selected}
key={individualAnswer}
/>
) )
}
</div>
)
}
}
// Again, destructring. Instead of (props) we use ({....})
// and pick our individual props here.
const EachIndividualAnswer = ({selected,individualAnswer, onClick}) => {
const handleClick = () => onClick(individualAnswer)
return (
<div>
<ul>
{
<li
onClick={handleClick}
className={
selected[individualAnswer] ? 'colored' : ''
}
>{individualAnswer}
</li>
}
</ul>
</div>
)
}
const rootElement = document.getElementById("root");
ReactDOM.render(<AnswerChoices />, rootElement);
.colored {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
I declared EachIndividualAnswer component as a functional one since it does not need to be a class. Also, I pass a handleClick prop for click event. With this handler, child sends the answer and parent component gets back it and updates its state. One prop EachIndividualAnswer gets is selected state. So it decides whether add a class or not. So, our selected state resides in SpecificAnswerChoice component and child gets it as a prop. Lastly, this component gets answers from its parent as you can see.

react.js deleting one of few rendered components

Here is my first post.
I am in processs of creating todo app.
My app is adding new task to task list when plus button is clicked , and after few clicks u got few task simple , but the problem is that each task got delete Icon , which unfortunately by my lack of sufficient skills is deleting all components instead of the one , which icon belongs to.
Here is App.js code
class App extends React.Component {
constructor(props){
super(props);
this.handleDelete = this.handleDelete.bind(this);
this.addTask = this.addTask.bind(this);
this.state = {taskNum: 0,
delete: false
}
}
addTask(){
this.setState({
taskNum: this.state.taskNum +1,
delete:false
});
}
handleDelete(e){
console.log(e.target);
this.setState({delete: true});
}
render() {
const tasks = [];
for (let i = 0; i < this.state.taskNum; i += 1) {
tasks.push(!this.state.delete && <Task key={i} number={i} deleteTask={this.handleDelete}/>);
};
return (
<div className="ui container content">
<h2 className="centerHeader header">TODO LIST</h2>
<h3 className="taskheader secondaryHeader">Tasks <Icon className="addNew plus" action={this.addTask}/></h3>
<div className="ui container five column grid taskList">
{tasks}
</div> ...
and here is Task.js
export class Task extends React.Component {
constructor(props){
super(props);
this.dataChanged = this.dataChanged.bind(this);
this.state ={message: 'TASK' + (this.props.number+1),
}
}
customValidateText(text) {
return (text.length > 0 && text.length < 31);
}
dataChanged(data) {
console.log(data.message);
this.setState({message: data.message});
}
render(){
const centerRow = classNames('textCenter', 'row');
return (<div className="ui column task">
<div className={centerRow}><InlineEdit
validate={this.customValidateText}
activeClassName="editing"
text={this.state.message}
paramName="message"
change={this.dataChanged}
style={{
background: 'inherit',
textAlign:'center',
maxWidth: '100%' ,
display: 'inline-block',
margin: 0,
padding: 0,
fontSize: '1em',
outline: 0,
border: 0
}}
/></div>
<div className={centerRow}><Icon className="browser outline huge center"/> </div>
<div className={centerRow}><Icon className="large maximize"/><Icon className="large save saveTask"/><Icon className="large trash outline" action={this.props.deleteTask} /></div>
</div>
);
I thought of trying to e.target and select the parentNode but i am not sure if thats the proper solution since using react , so could u help me find efficient solution for this problem so that when trash icon is clicked it will delete only parent component.
One of the main reasons why react is powerful is that it give you the ability to maintain your DOM based on you data without having to do any manipulation to the DOM by yourself
So for your example to be more React JS friendly you need to do some changes, that will also fix your problem
1- You need to keep an actual state of your data, so adding a todo item means an actual real data added to your program, not just a component representation.
2- Removing a task represented by a component means removing the data it self, so deleting one of the tasks means deleting its actual data, and then react will handle updating the DOM for you, so the idea of a flag to hide a component is not React JS way
3- The way react knows when to render and how to handle all your data is managed by the component state .. so you save your data in component state and you only need to care about updating the state, then react will know that it will need to render again but now with the new updated list of tasks
I did some changes in your code with commented lines explaining why
class App extends React.Component {
constructor(props){
super(props);
this.handleDelete = this.handleDelete.bind(this);
this.addTask = this.addTask.bind(this);
this.state = {
tasks: [ ], // this is the array that will hold the actual data and based on its content react will handle rendering the correct data
counter : 1 // this counter is incremented every task addition just to make sure we are adding different task name just for the example explanation
}
}
}
addTask(){
this.setState({
tasks: this.state.tasks.push( "TASK" + counter); //This how we add a new task as i said you are adding an actual task data to the state
counter : this.state.counter + 1 //increment counter to have different task name for the next addition
});
}
//i changed this function to accept the task name so when you click delete it will call this function with task name as parameter
//then we use this task name to actually remove it from the tasks list data in our state
handleDelete(taskToDelete){
this.setState({
//the filter function below will remove the task from the array in our state
//After this state update, react will render the component again but now with the tasks list after removing deleting this one
tasks : this.state.tasks.filter((task) => {
if(task != taskToDelete)
return word;
})
});
}
render() {
const tasks = [];
//Notice here we pass an actual data to every Task component so i am adding prop message to take the value from this.state.tasks[index]
for (let i=0 ; i< this.state.tasks.length ; i++)
{
tasks.push(<Task key={i} message={this.state.tasks[i]} deleteTask={this.handleDelete}/>);
}
return (
<div className="ui container content">
<h2 className="centerHeader header">TODO LIST</h2>
<h3 className="taskheader secondaryHeader">Tasks <Icon className="addNew plus" action={this.addTask}/></h3>
<div className="ui container five column grid taskList">
{tasks}
</div> ...
)
}
}
Task Component
export class Task extends React.Component {
constructor(props){
super(props);
this.dataChanged = this.dataChanged.bind(this);
this.removeCurrentTask = this.removeCurrentTask.bind(this);
//Here i am setting the state from the passed prop message
this.state ={
message: this.props.message
}
}
customValidateText(text) {
return (text.length > 0 && text.length < 31);
}
dataChanged(data) {
console.log(data.message);
this.setState({message: data.message});
}
removeCurrentTask (){
//calling the deleteTask function with the current task name.
this.props.deleteTask(this.state.message);
}
render(){
const centerRow = classNames('textCenter', 'row');
return (
<div className="ui column task">
<div className={centerRow}><InlineEdit
validate={this.customValidateText}
activeClassName="editing"
text={this.state.message}
paramName="message"
change={this.dataChanged}
style={{
background: 'inherit',
textAlign:'center',
maxWidth: '100%' ,
display: 'inline-block',
margin: 0,
padding: 0,
fontSize: '1em',
outline: 0,
border: 0
}}
/></div>
<div className={centerRow}><Icon className="browser outline huge center"/> </div>
//Notice the action handler here is changed to use removeCurrentTask defined in current component
//BTW i don't know how Icon is handling the action property ... but now you can simply use onClick and call removeCurrentTask
<div className={centerRow}><Icon className="large maximize"/><Icon className="large save saveTask"/><Icon className="large trash outline" action={this.removeCurrentTask} /></div>
</div>
);
}
}

Rendering a list of items in React with shared state

Original Question
I'm trying to render a list of items using React. The key is that the items share a common state, which can be controlled by each item.
For the sake of simplicity, let's say we have an array of strings. We have a List component that maps over the array, and generates the Item components. Each Item has a button that when clicked, it changes the state of all the items in the list (I've included a code snippet to convey what I'm trying to do).
I'm storing the state at the List component, and passing down its value to each Item child via props. The issue I'm encountering is that the button click (within Item) is not changing the UI state at all. I believe the issue has to do with the fact that items is not changing upon clicking the button (rightfully so), so React doesn't re-render the list (I would have expected some kind of UI update given the fact that the prop isEditing passed onto Item changes when the List state changes).
How can I have React handle this scenario?
Note: there seems to be a script error when clicking the Edit button in the code snippet, but I don't run into it when I run it locally. Instead, no errors are thrown, but nothing in the UI gets updated either. When I debug it, I can see that the state change in List is not propagated to its children.
Edited Question
Given the original question was not clear enough, I'm rephrasing it below.
Goal
I want to render a list of items in React. Each item should show a word, and an Edit button. The user should only be able edit one item at a time.
Acceptance Criteria
Upon loading, the user sees a list of words with an Edit button next to each.
When clicking Edit for item 1, only item 1 becomes editable and the Edit button becomes a Save button. The rest of the items on the list should no longer show their corresponding Edit button.
Upon clicking Save for item 0, the new value is shown for that item. All the Edit buttons (for the rest of the items) should become visible again.
Problem
On my original implementation, I was storing an edit state in the parent component (List), but this state wasn't properly being propagated to its Item children.
NOTE: My original implementation is lacking on the state management logic, which I found out later was the main culprit (see my response below). It also has a bind bug as noted by #Zhang below. I'm leaving it here for future reference, although it's not really a good example.
Here's my original implementation:
const items = ['foo', 'bar'];
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
isEditing: false
};
}
toggleIsEditing() {
this.setState((prevState) => {
return {
isEditing: !prevState.isEditing
}
});
}
render() {
return (
<ul>
{items.map((val) => (
<Item value={val}
toggleIsEditing={this.toggleIsEditing}
isEditing={this.state.isEditing}/>
))}
</ul>
);
}
}
class Item extends React.Component {
render() {
return (
<li>
<div>
<span>{this.props.value}</span>
{ !this.props.isEditing &&
(<button onClick={this.props.toggleIsEditing}>
Edit
</button>)
}
{ this.props.isEditing &&
(<div>
<span>...Editing</span>
<button onClick={this.props.toggleIsEditing}>
Stop
</button>
</div>)
}
</div>
</li>
);
}
}
ReactDOM.render(<List />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<body>
<div id="app" />
</body>
you didn't bind the parent scope when passing toggleIsEditing to child component
<Item value={val}
toggleIsEditing={this.toggleIsEditing.bind(this)}
isEditing={this.state.isEditing}/>
I figured out the solution when I rephrased my question, by rethinking through my implementation. I had a few issues with my original implementation:
The this in the non-lifecycle methods in the List class were not bound to the class scope (as noted by #ZhangBruce in his answer).
The state management logic in List was lacking other properties to be able to handle the use case.
Also, I believe adding state to the Item component itself was important to properly propagate the updates. Specifically, adding state.val was key (from what I understand). There may be other ways (possibly simpler), in which case I'd be curious to know, but in the meantime here's my solution:
const items = ['foo', 'bar'];
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
editingFieldIndex: -1
};
}
setEdit = (index = -1) => {
this.setState({
editingFieldIndex: index
});
}
render() {
return (
<ul>
{items.map((val, index) => (
<Item val={val}
index={index}
setEdit={this.setEdit}
editingFieldIndex={this.state.editingFieldIndex} />
))}
</ul>
);
}
}
class Item extends React.Component {
constructor(props) {
super(props);
this.state = {
val: props.val
};
}
save = (evt) => {
this.setState({
val: evt.target.value
});
}
render() {
const { index, setEdit, editingFieldIndex } = this.props;
const { val } = this.state;
const shouldShowEditableValue = editingFieldIndex === index;
const shouldShowSaveAction = editingFieldIndex === index;
const shouldHideActions =
editingFieldIndex !== -1 && editingFieldIndex !== index;
const editableValue = (
<input value={val} onChange={(evt) => this.save(evt)}/>
)
const readOnlyValue = (
<span>{val}</span>
)
const editAction = (
<button onClick={() => setEdit(index)}>
Edit
</button>
)
const saveAction = (
<button onClick={() => setEdit()}>
Save
</button>
)
return (
<li>
<div>
{ console.log(`index=${index}`) }
{ console.log(`editingFieldIndex=${editingFieldIndex}`) }
{ console.log(`shouldHideActions=${shouldHideActions}`) }
{
shouldShowEditableValue
? editableValue
: readOnlyValue
}
{
!shouldHideActions
? shouldShowSaveAction
? saveAction
: editAction
: ""
}
</div>
</li>
);
}
}
ReactDOM.render(<List />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<body>
<div id="app" />
</body>

Categories

Resources