Solar1407
Solar1407

Reputation: 85

Map an array of string to component states in React-Native/ES6

I have a component like this:

export default class Demo extends Component{
    constructor(props){
        super(props)
        this.state = {
           str1: '',
           str2: '',
           str3: '',
           str4: '',
        }
    }

........
}

And the string is like aaa-bbb-ccc-dd

How can I split them and add to the component state. My goal is something like:

str1: 'aaa',
str2: 'bbb',
str3: 'ccc',
str4: 'dd'

Upvotes: 1

Views: 1261

Answers (3)

Prince Hernandez
Prince Hernandez

Reputation: 3731

Create a new object using reduce and then use this.setState() to finally set the state in just one simple movement.

Also notice that it is more performant to set the state just once and use the function provided by react. Setting the state directly like state[bar] = foo is a bad practice as the documentation says

let string = "aaa-bbb-ccc-dd";

const newState = string.split('-').reduce((a, c, i) => {
    a[`str${i+1}`] = c;
    return a;
}, {})

this.setState(newState)

Upvotes: 2

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92547

Try

let s = "aaa-bbb-ccc-dd";

let state = {}
        
s.split('-').forEach((x,i)=> state[`str${i+1}`]=x )

console.log(state);

// and set state using this.setState(state) 

Upvotes: 1

Md Johirul Islam
Md Johirul Islam

Reputation: 5162

Something like the following should work:

const str = "aaa-bbb-ccc-dd"; 
const arr = srt.split("-");   
this.setState({str1 : arr[0],str2 : arr[1], str3: arr[2], str4 : arr[3]});

Upvotes: 1

Related Questions