I have a display area(which is a div) where I rendered some text(using span ).I used map function to render the text from an array .
The problem is when I add color class to span inside map function every text gets the same color(I know why its happening) but I only want the specific text(single word I target) to take the color and the remaining will stay the same. Can't think of any solution for this .
[colorTrigger is the word that I want to color.]
here is sample code -
<div className = "firstLine">
{display.map(word=>{
if(colorTrigger){
return (<span key={uuid()} className = "singleWord redColorWord" >{word}</span>)
}
return(<span key={uuid()} className = "singleWord" >{word}</span>)
})}
You can put a condition on the className itself. i don't know what the colorTrigger is, but as per your question you can check if its present or not . similar to your if loop applied on the className conditionally.
<div className="firstLine">
{
display.map(word=>{
return (<span key={uuid()}
className={`${word === 'colorTrigger' ? 'redColorWord' : null}
singleWord`}>
{word}
</span>)
})
}
</div>
Related
Code
export default function Header(){
let showMe = false;
function toggle(){
showMe = !showMe;
}
return (
<>
<button onClick={toggle}>Toggle Subjects</button>
{/*The bottom code should toggle on and off when the button is pressed*/}
<div style={{
display: showMe?"block":"none"
}}>
This should toggle my display
</div>
</>
);
}
Expectation
The div tag should toggle in visibility (For example, if I clicked on the button once, the div tag should show up, and if I clicked on it again it would be hidden and so on).
Reality
It appears the variable showMe changes however the div tag does not follow with the updates and remains hidden.
NOTE: I am using next.js if that changes anything.
showMe needs to be a state variable so that React knows to rerender the component when showMe changes. I'd read this: https://reactjs.org/docs/hooks-state.html
The code below should work (note how showMe is replaced with a call to useState).
export default function Header(){
const [showMe, setShowMe] = useState(false);
function toggle(){
setShowMe(!showMe);
}
return (
<>
<button onClick={toggle}>Toggle Subjects</button>
{/*The bottom code should toggle on and off when the button is pressed*/}
<div style={{
display: showMe?"block":"none"
}}>
This should toggle my display
</div>
</>
);
}
The bracket notation const [showMe, setShowMe] = useState(false); is Array Destructuring: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
useState returns an array of length 2. Using array destructuring, we set the first element of the returned array to showMe and the second element of the returned array to setShowMe.
I'm very new to the language of react. I seem to continuously get an unexpected token error on the ":". What exactly is the syntax for putting multiple styles inside the Box component shown below? Alongside that, how does one go about putting multiple of these Box components, each one having its margin changed and put inside of an array, displayed on a website.
ncaught SyntaxError: /Inline Babel script: Unexpected token, expected "}" (51:73)
const Box = (props) => <div style={"margin-left" : props.spacing, "width" : props.width, "height" : props.height, "background-color" : props.color}></div>
|
^
The box component takes multiple sub-components such as margin-left (I'm not even sure if I can use this within React) and so on. I then have a for loop that continuously adds box components to an array each with a different margin so that it ends up really displaying a row of different elements inside the div.
class StoryPage extends React.Component {
render(){
const Box = (props) => <div style={"margin-left" : props.spacing; "width" : props.width; "height" : props.height; "background-color" : props.color;}></div>
const val = 0
const boxArray = []
for(let i = 0; i < 10; i++){
val += 100
boxArray.push(<Box spacing = {val} width = "100px" height = "100px" color = "black" />)
}
return(
<div>
{boxArray}
</div>
)
}
}
What I essentially expect to happen is have the array of box elements be displayed. However, I'm not really sure how I'm supposed to go about doing this.
Your “passing an object literal as a prop”-syntax is wrong — explanation below.
React props are passed as follows:
string literal
<Component strProp='hello' />
// or
<Component strProp={'hello'} />
variable
<Component strProp={this.props.foo} />
array literal
<Component arrProp={[1, 2, 3]} />
object literal
<Component objProp={{foo: 'bar'}} />
See the double curly-brackets? One pair is needed to enclose any non-string-literal expression passed as prop, and the other is simply part of the object literal notation.
In contrast, this:
<Component objProp={foo: 'bar'} /> // <- WRONG
would not work because foo: 'bar' is not an expression.
Hugo is right. Also you don't want to add larger margin lefts to each element, margin-left specifies distance from border to element on the left. https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model
You can set the property display to "inline" on all your divs to change the layout of divs from block to inline. Or just not do anything and they'll still all display.
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout
Your problem is this line:
const Box = (props) => <div style={"margin-left" : props.spacing; "width" : props.width; "height" : props.height; "background-color" : props.color;}></div>
You have provide wrong style attribute, you need to provide like this:
const Box = (props) => (
<div
style={{
marginLeft: props.spacing,
width: props.width,
height: props.height,
backgroundColor: props.color
}}
/>
);
Notice that style attribute should contain double curly braces and should separate properties with a comma ,
Demo
Note: In React, inline style name should be in camelCase.
For Example,
margin-left should be marginLeft.
background-color should be backgroundColor.
I am basically wanting to do individual selected states on divs that I am rendering in a loop. I can only see a way to change the color of all of the rendered divs, but rather I wish to change the color of which ever one was clicked. Below is the code for the loop.
renderSports() {
const {sports} = this.props
return sports.valueSeq().map(sport => this.renderActualSports(sport))
},
renderActualSports(sport) {
const {sportCount} = this.props
return (
<div className="sportSeparator">
{sport} {this.renderCount(sportCount.get(sport))}
</div>
)
},
This will basically just render a list of some sports. I want to change the color of a selected sport on click.
You will need to store the items that were clicked in your component state.
Assuming you would store this highlighted items in this.state.highlighted and that your sport variable is a string or number:
renderActualSports(sport) {
const {sportCount} = this.props
return (
<div
className="sportSeparator"
onClick={this.highlight(sport)}
style={{color: this.state.highlighted.indexOf(sport) > -1 && 'red' : ''}}
>
{sport} {this.renderCount(sportCount.get(sport))}
</div>
)
},
highlight(sport) {
return () => {
this.setState({highlighted: [...this.state.highlighted, sport]});
}
}
So what you are doing is onClick on the div you add that sport to the this.state.highlighted array and when displaying the list. you check if that sport is in the array and if yes you change the color using an inline style
You don't have to read the whole code, just read the comment in the editQuantity function and in showOrderItem function, specially in the showOrderItem function and my problem is i think just silly, as both of my function are working as they supposed to work,
*editQuantity function supposed to change the state, it changing it, i checked by adding the console line.
*showOrderItem function supposed display the item, he is doing that job as well.
My problem is, i try to add conditional rendering in the showOrderItem function that not working, even though i am able to change the state.
Please read the comment in showOrderItem function, to see where is the problem:
import React from 'react';
export default class ShowOrder extends React.Component{
constructor(props){
super(props);
this.state={
quantityEditing:this.props.orderItems,
}
}
editQuantity(item){
const order=this.state.quantityEditing;
for(var i =0; i<order.length; i++){
if(order[i].item==item){
console.log(order[i].orderQuantityEditing)
order[i].orderQuantityEditing=true;
this.setState({order:this.state.quantityEditing})
console.log(order[i].orderQuantityEditing)
}
}
}
showOrderItem(){
const style = {cursor:'pointer'}
const orderItems=this.state.quantityEditing;
console.log(orderItems)
const orderItem=orderItems.map((item,index)=>
<p>
{orderItems.orderQuantityEditing ? 'some':
<span style={style} onClick={this.editQuantity.bind(this,item.item)}>
//as you can see in here i added conditional rendering, that if orderItems.orderQuantityEditing is true display me some, but that's not working --orderItems.orderQuantityEditing ? 'some'(this part) does not matter how many times i click on property it never display me my string 'some'
{item.quantity}</span>}
<span style={style}> {item.item}</span>
<span style={style}> Q</span>
<span style={style}> N</span>
<span style={style}> X</span>
</p>
);
return orderItem;
}
render(){
return(
<div>
{this.showOrderItem()}
</div>
);
}
}
Instead of
{orderItems.orderQuantityEditing ?
'some'
:
<span style={style} onClick{this.editQuantity.bind(this,item.item)}>
I think you need to write this:
{item.orderQuantityEditing ?
'some'
:
<span style={style} onClick={this.editQuantity.bind(this,item.item)}>
Because you are using map, and item will be each object of array, so you need to use item to access that property. During the for loop, when changing the state you wrote:
order[i].orderQuantityEditing=true;
That it proper, order will be an array and you need to provide the index to access particular object of that.
I am confused about this for a long time.
Here is the case:
1, I create a table with multiple rows, in this way:
tableRow(basicInfoArray) {
return basicInfoArray.map((basicInfo, index) => (
<tr
key={basicInfo._id}
className={index % 2 === 0 ? 'alt' : null}
onClick={event => this.props.showDetail(basicInfo._id, event)}
>
<td>{basicInfo.mentee_id}</td>
<td>{`${basicInfo.firstname} ${basicInfo.lastname}`}</td>
<td>{basicInfo.othername}</td>
<td>{basicInfo.location}</td>
</tr>
));
}
As you can see, I bind a onClick event to each row. If the row is clicked, it will highlight, and there will be a drilldown to show detail information.
The question is here, after clicked on the backdrop(which bind a onClick event), the drilldown hide and I should remove the highlight effect from the row. Currently I use this way:
const highLightRows = document.getElementsByClassName('highLight');
for (let i = 0; i < highLightRows.length; i += 1) {
highLightRows[i].classList.toggle('highLight');
}
As the documents of React.js says that it's not a good practice to manipulate the dom directly, the UI change should be caused by the props/state change. Obviously it's not a good idea to bind a state for each row of the table because of the quantity. What's the best practice to do this?
It's important to keep in mind that react renders whatever you have in memory, in this case you have an array of items that you want to display in a table, when clicking any of those items you want to highlight the selected, right?
Well, for that you could define a property in each element of the array called selected, this property will be true/false depending on the user selection, then when rendering the row you will check for this property and if it's there you will assign thehighLight class or not. With this approach you will only need to worry to change the value of this property on memory and it will automatically get highlighted on the DOM.
Here's an example:
renderRow(info, index) {
const styles = [
index % 2 === 0 ? 'alt' : '',
info.selected = 'highLight' : '',
];
return (
<tr
key={info._id}
className={styles.join(' ')}
onClick={event => this.props.showDetail(info, event)}
>
<td>{basicInfo.mentee_id}</td>
<td>{`${info.firstname} ${info.lastname}`}</td>
<td>{info.othername}</td>
<td>{info.location}</td>
</tr>
);
}
renderContent(basicInfoArray) {
return basicInfoArray.map((basicInfo, index) => this.rendeRow(basicInfo, index));
}
Just make sure to set to true the selected property on showDetail function, and then set to false when you need to hide and remove the highLight class.
Good luck!