how does a component gets props from a reducer in redux(how does the connect function work) Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of how does a component gets props from a reducer in redux(how does the connect function work) without wasting too much if your time.

The question is published on by Tutorial Guruji team.

That’s a question for personal learning because I am struggling to learn this part from online resources I am creating a component that gets its props from a reducer, and I know that the store and actions are the things that link those props to the requested component but I don’t understand how this happens(via javascript)

here’s the songsReducer:

import {combineReducers} from 'redux';
import { selectSong } from '../actions';

const songsReducer = () =>{
    return [
{title:'myImmortal',duration:'4:05'},
{title:'BringMeToLife',duration:'2:05'},
{title:'IWantItThatWay',duration:'2:35'},
{title:'YourStar',duration:'4:35'},
    ]
}
const selectedSongReducer = (selectedSong=null,action) =>{
if(action.type==='SONG_SELECTED'){
    return action.payload;
}
return selectedSong;
}

export default combineReducers({
    songs: songsReducer,
    selectedSong:selectedSongReducer
})

it should give these props to the SongList.js component via the connect function as in this syntax:

import React,{Component} from 'react'
import {connect} from 'react-redux'

class SongList extends React.Component{
render(){
    return <div>SongList</div>
}
}

const mapStateToProps =(state)=>{

console.log(state)
return {songs:state.songs}
}

export default connect(mapStateToProps)(SongList);

In ‘mapStateToProps’ when we logged state to the console it was holding the array ‘songs’ resulting from ‘songsReducer’ and I didn’t understand how that javascript syntax could give that result.

can someone help me learn more about this?

Answer

The connect function simply takes your redux state and injects it to the component’s props. After it injects it, you could easily access it on the props object. So, in your case, you would access the songs state like this:

this.props.songs
We are here to answer your question about how does a component gets props from a reducer in redux(how does the connect function work) - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji