How to add elements dynamically using redux

Viewed 1357

Hi I am trying to create a simple form builder using react + redux.

I am facing an issue with adding elements dynamically from the sidebar to the container.

action.js

export const addNewTextBox = () => {
    return {
        type: 'ADD_NEW_TEXT_BOX'
    };
}

export const addNewName = () => {
    return {
        type: 'ADD_NEW_NAME'
    };
}

export const updateChildren = (child) => {
    return {
        type: 'UPDATE_CHILDREN',
        child
    };
}

addElementsReducer.js

const initialState = {
  addFormElementsVisible: false,
  textBoxNum: 0,
  nameNum: 0,
  childKey: 0,
  children: []
}

const addElements = (state = initialState, action) => {
    switch (action.type) {
    case 'ADD_NEW_TEXT_BOX':
        return Object.assign({}, state, {
            textBoxNum: state.textBoxNum + 1,
            childKey: state.childKey + 1,
        });
    case 'ADD_NEW_NAME':
        return Object.assign({}, state, {
            nameNum: state.nameNum + 1,
            childKey: state.childKey + 1,
        });
    case 'UPDATE_CHILDREN':
        return Object.assign({}, state, {
            children: state.children.concat([action.child])
        });
    default:
        return state
    }
}

export default addElements;

The above reducer and action is being passed in my Layout.js file which renders the sidebar and the container for adding elements.

Layout.js

<Sidebar
textBoxNum={this.props.textBoxNum}
nameNum={this.props.nameNum}
childKey={this.props.childKey}
updateChildren={this.props.actions.updateChildren}
addNewTextBox={this.props.actions.addNewTextBox}
addNewName={this.props.actions.addNewName}/>

<Create children={this.props.children}/>

From create I am sending children to ElementsContainer.js

<div>
    <div className="new_elements">
        {(() => {
           this.props.children.map((child) => {
               return (
                  <JsxParser
                      components={[TextBox]}
                      jsx={child}
                  />
               );
            })
         })()}
      </div>
   </div>

this.props.children renders an array of elements from the sidebar.

How do I push the elements from my sidebar to the childrens array and render it on my container?

If this is a duplicate kindly guide me to the solution. If this is not enough, kindly let me know what more clarification can I provide on my question. Thanks in advance.

3 Answers
Related