abu abu
abu abu

Reputation: 7026

Pass text value to another component

How to pass text value to another component using Redux in React?

I am learning Redux in React. I am trying to pass text value to another component using Redux in React.

My code is like below

Mycomponent.js

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

class Mycomponent extends Component {
    state = {
        textInput: '',
    }

    handleChange = event => {
        this.props.dispatch({ type: "add" });
    }

    render = () => {        
        return (
            <div>
                <input
                    type="text"
                    onChange={this.handleChange} />
            </div>
        );
    }
}

const mapStateToProps = state => ({ nameState: state.nameState});

export default connect(mapStateToProps)(Mycomponent);

nameAction.js

export const nameAction = () => ({
    type: 'add'
});

export default { nameAction };

nameReducer.js

const nameReducer = (state = {}, action) => {
    switch (action.type) {
        case 'add': {
            return {
                ...state,
                nameState: action.payload
            };
        }
        default:
            return state;
    }
};

export default nameReducer;

Outputcomponent.js

import React, { Component } from 'react';

class Outputcomponent extends Component {
    render = (props) => {
        return (
            <div>
                <div>{this.props.nameState }</div>
            </div>
        );
    }
}

export default Outputcomponent;

Upvotes: 0

Views: 748

Answers (2)

Daphaz
Daphaz

Reputation: 506

The use of redux hooks explained by Josiah is for me the best approach but you can also use mapDispatchToProps.

Even if the main problem is that you don't pass any data in your 'add' action.

nameAction.js

You call the action.payload in nameReducer.js but it does not appear in your action

export const nameAction = (text) => ({
  type: 'add',
  payload: text
});

Mycomponent.js

Then as for your state we can mapDispatchToProps.

(I think it's better to trigger the action with a submit button and save the input change in your textInput state, but I guess it's intentional that there is none)

import React, { Component } from 'react';
import { connect } from 'react-redux';
import {nameAction} from './nameAction'

class Mycomponent extends Component {
    state = {
        textInput: '',
    }

    handleChange = event => {
        this.props.nameAction(event.target.value);
    }

    render = () => {        
        return (
            <div>
                <input
                    type="text"
                    onChange={this.handleChange} />
            </div>
        );
    }
}

const mapStateToProps = state => ({ nameState: state.nameState});

const mapDispatchToProps = dispatch => ({ nameAction: (text) => dispatch(nameAction(text))});

export default connect(mapStateToProps,mapDispatchToProps)(Mycomponent);

OutputComponent.js

to get the data two possibilities either with a class using connect and mapStateToProps , or using the useSelector hook with a functional component.

with a Class

import React, { Component } from "react";
import { connect } from "react-redux";

class OutputComponent extends Component {
    render = () => {
        return (
            <div>
                <div>{this.props.nameState}</div>
            </div>
        );
    };
}

const mapStateToProps = state => state;

export default connect(mapStateToProps)(OutputComponent);

with a functional component

import React from "react";
import { useSelector } from "react-redux";

const OutputComponent = () => {
    const nameState = useSelector((state) => state.nameState);
    return (
        <div>
            <div>{nameState}</div>
        </div>
    );
};

export default OutputComponent;

Of course you must not forget to create a strore and to provide it to the highest component

store.js

import { createStore } from "redux";
import nameReducer from "./nameReducer";

const store = createStore(nameReducer);

export default store;

index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store";

ReactDOM.render(
        <Provider store={store}>
            <App />
        </Provider>,
    document.getElementById("root")
);

Upvotes: 2

Josiah Nyarega
Josiah Nyarega

Reputation: 703

Component

const AddTodo = () => {
  const [todo, setTodo] = useState("");
  const dispatch = useDispatch();
  
  const handleChange = (e) => setTodo(e.target.value);
  const handleSubmit = (e)  => {
    e.preventDefault();
    dispatch(addTodoAction(todo));
  } 

  return {
    <form onSubmit={handleSubmit}>
      <input type="text" onChange={handleChange} />
    </form>
  }
)

Actions

const addTodoAction = (text) => {
   dispatch({
    type: "ADD_TODO",
    payload: text
   })
}

Reducers

const addTodoReducer = (state, action) => {
  switch(action.type) {
    case "ADD_TODO":
      return {
        todo: action.payload,
      }
    default:
      return state;
  }
}

store

 // some code for store.js

Accessing this todo from another component

  const ComponentA = () => {
    const {todo} = useSelector(state => state.todo);

   return (
     <p> {todo} </p>
   )
  }

Side Note:

  • Redux comes with too much boilerplate if you want to pass text from one component to another, just use props

Upvotes: 1

Related Questions