Radu Olteanu
Radu Olteanu

Reputation: 443

How to update the state for a custom component in React-Admin

I have the following scenario: using react-admin infrastructure, for a Resource, I have the following Edit View :

import Editor from "react-simple-code-editor";

export const CodeQuestionEdit = props => (
  <Edit {...props}>
    <SimpleForm>
      <LongTextInput source="text" />
      <TextField label="Code Block" />
      <FormDataConsumer>
        {({ formData }) => (
          <Editor
            value={formData.codeBlock}
            onValueChange={code => {
              //Update the current edit form ....
            }}
            highlight={code =>
              highlight(code, languages.cs)
                .split("\n")
                .map(
                  line =>
                    `<span class="container_editor_line_number">${line}</span>`
                )
                .join("\n")
            }
            padding={10}
            className="container__editor"
          />
        )}
      </FormDataConsumer>
    </SimpleForm>
  </Edit>
);

Editor component is not part of the react-admin, how can I update the state of the Editor with what the user types? and then pass this value back to the higher component, so when I save, I expect to have the last value typed passed in.

Upvotes: 0

Views: 2128

Answers (1)

Adam Šulc
Adam Šulc

Reputation: 546

If you want to save the value of user input to state and work with it later, you can use onChange attribute.

A simple example you can implement for your component may look like this:

First you need a method that will save the value from input to state.

handleChange = (event) => {
   this.setState({ yourState: event.target.value });
};

Then you need to just set the onChange attribute to your input.

And since your component is wrapped in react-admin Edit, the saving process should be secure.

Upvotes: 1

Related Questions