How to Separate String and Push to React State

split a string by newline in react

In your case JSX does not interpret "<br />" as a HTML tag, but as a string, so

<td>
{
order.expeditionPlaces
? order.expeditionPlaces.split(",").join("<br>")
: ""
}
</td>

should be

<td>
{
order.expeditionPlaces
? order.expeditionPlaces.split(",").map(place => <p> {place} </p>)
: ""
}
</td>

split string within react if statement

Just replace this

{order.expeditionPlaces.split(",").join("<br />")}

With

{order.expeditionPlaces ? order.expeditionPlaces.split(",").join("<br />") : ''}

How can I insert into React's state array with setState?

enter image description here

Clone the current state using slice(). By doing this, the original state remains unaffected till setState(). After cloning, do your operations over the cloned array and set it in the state. The previous answer will mutate the state. Read about this here

let a = this.state.arr.slice(); //creates the clone of the state
a[index] = "random element";
this.setState({arr: a});

Split String into various Text elements

Try this:

highlightWord( word , search ){

var newWord = word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");

if ( search.toLowerCase().indexOf(newWord.toLowerCase()) != -1 ){ // if word in question
// highlight it
return <Text style={{fontWeight:'bold'}}>{word}</Text>
}
else{
return <Text>{word}</Text>
}
}

renderRow( question ){

let split = question.title.split(' '); //divide question in words
textViews = [];
for (var i=0 ; i<split.length ; i++){
var word = split[i]; // get words
textViews.push( highlightWord(word,this.state.searchInput) );
}

// return all words together (highlighted or not)
return <View style={{flexDirection:'row'}}>{ textViews }</View>
}

EDIT

I added the first line on highlightWord to handle words with punctuation characters.

How to push to a map value array and use it as state in React?

Please try this. Here I used separate variable to store data and set that variable into the state at last.

let mapObj = new Map();

tasks.forEach((task) => {
const key = `${week.year}-${week.weekNo}`;

if (!mapObj.has(key)) {
mapObj.set(key, []);
}
mapObj.get(key).push(task);
});

setTasksMap(mapObj);


Related Topics



Leave a reply



Submit